Java:MyBatis动态SQL实践(2)

简介: Java:MyBatis动态SQL实践

实体Person.java

package com.mouday.pojo;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Person {
    private Integer id;
    private String name;
    private Integer age;
}

mapper接口 PersonMapper.java

package com.mouday.mapper;
import com.mouday.pojo.Person;
import java.util.List;
public interface PersonMapper {
    List<Person> selectAll();
    /**
     * 根据输入的信息进行条件检索
     * 1. 当只输入用户名时, 使用用户名进行 【模糊检索】
     * 2. 当只输入年龄时, 使用性别进行 【完全匹配】
     * 3. 当用户名和年龄都存在时, 用这两个条件进行查询匹配的用
     */
    List<Person> selectByPersonSelective(Person person);
    /**
     * 更新非空属性
     */
    int updateByPrimaryKeySelective(Person person);
    /**
     * 插入非空字段
     */
    int insertSelective(Person person);
    /**
     * 当 name 没有值时, 使用 name 进行查询
     * 否则使用 id 进行查询
     */
    List<Person> selectByNameOrId(Person person);
}

mapper映射文件 PersonMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mouday.mapper.PersonMapper">
    <sql id="Base_Column_List">
        id, name, age
    </sql>
    <select id="selectAll" resultType="Person">
    select
    <include refid="Base_Column_List"/>
    from person
    </select>
    <select id="selectByPersonSelective" resultType="Person" parameterType="Person">
        select
        <include refid="Base_Column_List" />
        from person
        <where>
            <if test="name != null and name !=''">
                and name like concat('%', #{name}, '%')
            </if>
            <if test="age != null">
                and age=#{age}
            </if>
        </where>
    </select>
    <update id="updateByPrimaryKeySelective" parameterType="Person">
    update person
    <set>
        <if test="name != null">
            `name` = #{name,jdbcType=VARCHAR},
        </if>
        <if test="age != null">
            `age` = #{age,jdbcType=INTEGER},
        </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
    </update>
    <insert id="insertSelective" parameterType="Person">
        insert into person
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                `name`,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <select id="selectByNameOrId" resultType="Person" parameterType="Person">
        select
        <include refid="Base_Column_List" />
        from person
        where 1=1
        <choose>
            <when test="id != null">
                and id=#{id}
            </when>
            <otherwise>
                and name=#{name}
            </otherwise>
        </choose>
    </select>
</mapper>

mapper映射文件 PersonMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mouday.mapper.PersonMapper">
    <sql id="Base_Column_List">
        id, name, age
    </sql>
    <select id="selectAll" resultType="Person">
    select
    <include refid="Base_Column_List"/>
    from person
    </select>
    <select id="selectByPersonSelective" resultType="Person" parameterType="Person">
        select
        <include refid="Base_Column_List" />
        from person
        <where>
            <if test="name != null and name !=''">
                and name like concat('%', #{name}, '%')
            </if>
            <if test="age != null">
                and age=#{age}
            </if>
        </where>
    </select>
    <update id="updateByPrimaryKeySelective" parameterType="Person">
    update person
    <set>
        <if test="name != null">
            `name` = #{name,jdbcType=VARCHAR},
        </if>
        <if test="age != null">
            `age` = #{age,jdbcType=INTEGER},
        </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
    </update>
    <insert id="insertSelective" parameterType="Person">
        insert into person
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                `name`,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <select id="selectByNameOrId" resultType="Person" parameterType="Person">
        select
        <include refid="Base_Column_List" />
        from person
        where 1=1
        <choose>
            <when test="id != null">
                and id=#{id}
            </when>
            <otherwise>
                and name=#{name}
            </otherwise>
        </choose>
    </select>
</mapper>

测试文件PersonTest.java

package com.mouday;
import com.mouday.mapper.PersonMapper;
import com.mouday.pojo.Person;
import com.mouday.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
public class PersonTest {
    private SqlSession session;
    private PersonMapper mapper;
    @Before
    public void init() throws IOException {
        this.session = MyBatisUtil.getSqlSession();
        this.mapper = this.session.getMapper(PersonMapper.class);
    }
    @After
    public void destroy() {
        this.session.close();
    }
    @Test
    public void testSelect() {
        System.out.println(mapper.selectAll());
    }
    /**
     * 选择数据
     */
    @Test
    public void testSelectByStudentSelective() {
        Person person = new Person();
        System.out.println(mapper.selectByPersonSelective(person));
        // select id, name, age from person
        person.setName("操");
        System.out.println(mapper.selectByPersonSelective(person));
        // select id, name, age from person WHERE name like concat('%', ?, '%')
        person.setAge(25);
        System.out.println(mapper.selectByPersonSelective(person));
        // select id, name, age from person WHERE name like concat('%', ?, '%') and age=?
    }
    /**
     * 更新数据
     */
    @Test
    public void testUpdateByPrimaryKeySelective() {
        Person person = new Person();
        person.setId(1);
        person.setAge(26);
        mapper.updateByPrimaryKeySelective(person);
        // update person SET `age` = ? where id = ?
        session.commit();
        person.setName("刘禅");
        mapper.updateByPrimaryKeySelective(person);
        session.commit();
        // update person SET `name` = ?, `age` = ? where id = ?
    }
    /**
     * 插入数据
     */
    @Test
    public void testInsertSelective() {
        Person person = new Person();
        person.setName("司马懿");
        mapper.insertSelective(person);
        // insert into person ( `name` ) values ( ? )
        session.commit();
        person.setAge(26);
        mapper.insertSelective(person);
        // insert into person ( `name`, age ) values ( ?, ? )
        session.commit();
    }
    /**
     * 选择查询
     */
    @Test
    public void testSelectByNameOrId() {
        Person person = new Person();
        person.setName("司马懿");
        mapper.selectByNameOrId(person);
        // select id, name, age from person where 1=1 and name=?
        person.setId(1);
        mapper.selectByNameOrId(person);
        // select id, name, age from person where 1=1 and id=?
    }
}

Where

set 和 where 其实都是 trim 标签的一种类型

where 等价于

Where
set 和 where 其实都是 trim 标签的一种类型
where 等价于


表示当 trim 中含有内容时, 添加 where, 且第一个为 and 或 or 时, 会将其去掉。

而如果没有内容, 则不添加 where。


set 等价于


<trim prefix="SET" suffixOverrides=",">

 ...

</trim>



表示当 trim 中含有内容时, 添加 set, 且最后的内容为 , 时, 会将其去掉。而没有内容, 不添加 set


trim 的几个属性


prefix: 当 trim 元素包含有内容时, 增加 prefix 所指定的前缀

prefixOverrides: 当 trim 元素包含有内容时, 去除 prefixOverrides 指定的 前缀

suffix: 当 trim 元素包含有内容时, 增加 suffix 所指定的后缀

suffixOverrides:当 trim 元素包含有内容时, 去除 suffixOverrides 指定的后缀


参考

  1. 你用过Mybatis的动态SQL后,就知道写SQL有多爽了!
  2. https://mybatis.org/mybatis-3/zh/dynamic-sql.html
相关文章
|
9月前
|
监控 Java API
现代 Java IO 高性能实践从原理到落地的高效实现路径与实战指南
本文深入解析现代Java高性能IO实践,涵盖异步非阻塞IO、操作系统优化、大文件处理、响应式网络编程与数据库访问,结合Netty、Reactor等技术落地高并发应用,助力构建高效可扩展的IO系统。
254 0
|
9月前
|
SQL 缓存 安全
深度理解 Java 内存模型:从并发基石到实践应用
本文深入解析 Java 内存模型(JMM),涵盖其在并发编程中的核心作用与实践应用。内容包括 JMM 解决的可见性、原子性和有序性问题,线程与内存的交互机制,volatile、synchronized 和 happens-before 等关键机制的使用,以及在单例模式、线程通信等场景中的实战案例。同时,还介绍了常见并发 Bug 的排查与解决方案,帮助开发者写出高效、线程安全的 Java 程序。
477 0
|
9月前
|
并行计算 Java API
Java List 集合结合 Java 17 新特性与现代开发实践的深度解析及实战指南 Java List 集合
本文深入解析Java 17中List集合的现代用法,结合函数式编程、Stream API、密封类、模式匹配等新特性,通过实操案例讲解数据处理、并行计算、响应式编程等场景下的高级应用,帮助开发者提升集合操作效率与代码质量。
402 1
|
9月前
|
安全 Java API
Java 17 及以上版本核心特性在现代开发实践中的深度应用与高效实践方法 Java 开发实践
本项目以“学生成绩管理系统”为例,深入实践Java 17+核心特性与现代开发技术。采用Spring Boot 3.1、WebFlux、R2DBC等构建响应式应用,结合Record类、模式匹配、Stream优化等新特性提升代码质量。涵盖容器化部署(Docker)、自动化测试、性能优化及安全加固,全面展示Java最新技术在实际项目中的应用,助力开发者掌握现代化Java开发方法。
378 1
|
10月前
|
数据采集 机器学习/深度学习 Java
Java 大视界 —— Java 大数据在智慧交通停车场智能管理与车位预测中的应用实践(174)
本文围绕 Java 大数据在智慧交通停车场智能管理与车位预测中的应用展开,深入剖析行业痛点,系统阐述大数据技术的应用架构,结合大型体育中心停车场案例,展示系统实施过程与显著成效,提供极具实操价值的技术方案。
|
9月前
|
存储 搜索推荐 算法
Java 大视界 -- Java 大数据在智慧文旅旅游线路规划与游客流量均衡调控中的应用实践(196)
本实践案例深入探讨了Java大数据技术在智慧文旅中的创新应用,聚焦旅游线路规划与游客流量调控难题。通过整合多源数据、构建用户画像、开发个性化推荐算法及流量预测模型,实现了旅游线路的精准推荐与流量的科学调控。在某旅游城市的落地实践中,游客满意度显著提升,景区流量分布更加均衡,充分展现了Java大数据技术在推动文旅产业智能化升级中的核心价值与广阔前景。
|
人工智能 自然语言处理 前端开发
从理论到实践:使用JAVA实现RAG、Agent、微调等六种常见大模型定制策略
大语言模型(LLM)在过去几年中彻底改变了自然语言处理领域,展现了在理解和生成类人文本方面的卓越能力。然而,通用LLM的开箱即用性能并不总能满足特定的业务需求或领域要求。为了将LLM更好地应用于实际场景,开发出了多种LLM定制策略。本文将深入探讨RAG(Retrieval Augmented Generation)、Agent、微调(Fine-Tuning)等六种常见的大模型定制策略,并使用JAVA进行demo处理,以期为AI资深架构师提供实践指导。
1949 73
|
10月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
370 1
|
10月前
|
安全 Java API
Java 抽象类与接口在 Java17 + 开发中的现代应用实践解析
《Java抽象类与接口核心技术解析》 摘要:本文全面剖析Java抽象类与接口的核心概念与技术差异。抽象类通过模板设计实现代码复用,支持具体方法与状态管理;接口则定义行为规范,实现多态支持。文章详细对比了两者在实例化、方法实现、继承机制等方面的区别,并提供了模板方法模式(抽象类)和策略模式(接口)的典型应用示例。特别指出Java8+新特性为接口带来的灵活性提升,包括默认方法和静态方法。最后给出最佳实践建议:优先使用接口定义行为规范,通过抽象类实现代码复用,合理组合两者构建灵活架构。
308 2