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
相关文章
|
12月前
|
监控 Java API
现代 Java IO 高性能实践从原理到落地的高效实现路径与实战指南
本文深入解析现代Java高性能IO实践,涵盖异步非阻塞IO、操作系统优化、大文件处理、响应式网络编程与数据库访问,结合Netty、Reactor等技术落地高并发应用,助力构建高效可扩展的IO系统。
343 0
|
12月前
|
SQL Java 关系型数据库
在 RDB 上跑 SQL------SPL 轻量级多源混算实践 1
SPL 支持通过 JDBC 连接 RDB,可动态生成 SQL 并传参,适用于 Java 与 SQL 结合的各类场景。本文以 MySQL 为例,演示如何配置数据库连接、编写 SPL 脚本查询 2024 年订单数据,并支持参数过滤和 SQL 混合计算。脚本可在 IDE 直接执行或集成至 Java 应用调用。
|
11月前
|
SQL 关系型数据库 Java
SQL 移植--SPL 轻量级多源混算实践 7
不同数据库的 SQL 语法存在差异,尤其是函数写法不同,导致 SQL 移植困难。SPL 提供 sqltranslate 函数,可将标准 SQL 转换为特定数据库语法,实现 SQL 语句在不同数据库间的无缝迁移,支持多种数据库函数映射与自定义扩展。
|
11月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
585 18
|
12月前
|
SQL 缓存 安全
深度理解 Java 内存模型:从并发基石到实践应用
本文深入解析 Java 内存模型(JMM),涵盖其在并发编程中的核心作用与实践应用。内容包括 JMM 解决的可见性、原子性和有序性问题,线程与内存的交互机制,volatile、synchronized 和 happens-before 等关键机制的使用,以及在单例模式、线程通信等场景中的实战案例。同时,还介绍了常见并发 Bug 的排查与解决方案,帮助开发者写出高效、线程安全的 Java 程序。
582 0
|
12月前
|
并行计算 Java API
Java List 集合结合 Java 17 新特性与现代开发实践的深度解析及实战指南 Java List 集合
本文深入解析Java 17中List集合的现代用法,结合函数式编程、Stream API、密封类、模式匹配等新特性,通过实操案例讲解数据处理、并行计算、响应式编程等场景下的高级应用,帮助开发者提升集合操作效率与代码质量。
512 1
|
12月前
|
安全 Java API
Java 17 及以上版本核心特性在现代开发实践中的深度应用与高效实践方法 Java 开发实践
本项目以“学生成绩管理系统”为例,深入实践Java 17+核心特性与现代开发技术。采用Spring Boot 3.1、WebFlux、R2DBC等构建响应式应用,结合Record类、模式匹配、Stream优化等新特性提升代码质量。涵盖容器化部署(Docker)、自动化测试、性能优化及安全加固,全面展示Java最新技术在实际项目中的应用,助力开发者掌握现代化Java开发方法。
494 1
|
11月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
486 0
|
数据采集 机器学习/深度学习 Java
Java 大视界 —— Java 大数据在智慧交通停车场智能管理与车位预测中的应用实践(174)
本文围绕 Java 大数据在智慧交通停车场智能管理与车位预测中的应用展开,深入剖析行业痛点,系统阐述大数据技术的应用架构,结合大型体育中心停车场案例,展示系统实施过程与显著成效,提供极具实操价值的技术方案。