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
相关文章
|
6月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
415 18
|
6月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
151 0
|
8月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
402 1
|
9月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
941 5
|
9月前
|
SQL Java 数据库连接
Java中实现SQL分页的方法
无论何种情况,选择适合自己的,理解了背后的工作原理,并能根据实际需求灵活变通的方式才是最重要的。
251 9
|
10月前
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1392 0
|
11月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
11月前
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
11月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
11月前
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
340 0