广告
返回顶部
首页 > 资讯 > 精选 >Fluent MyBatis怎么实现动态SQL
  • 630
分享到

Fluent MyBatis怎么实现动态SQL

2023-06-20 19:06:21 630人浏览 独家记忆
摘要

这篇文章主要讲解了“Fluent mybatis怎么实现动态sql”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Fluent MyBatis怎么实现动态SQL”吧!目录数据准备代码生成在 W

这篇文章主要讲解了“Fluent mybatis怎么实现动态sql”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Fluent MyBatis怎么实现动态SQL”吧!

目录
  • 数据准备

  • 代码生成

    • 在 WHERE 条件中使用动态条件

    • 在 UPDATE 使用动态更新

    • choose 标签

MyBatis 令人喜欢的一大特性就是动态 SQL。在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的,
MyBatis虽然提供了动态拼装的能力,但这些写xml文件,也确实折磨开发。Fluent MyBatis提供了更贴合Java语言特质的,对程序员友好的Fluent拼装能力。

Fluent MyBatis动态SQL,写SQL更爽

数据准备

为了后面的演示, 创建了一个 Maven 项目 fluent-mybatis-dynamic, 创建了对应的数据库和表

DROP TABLE IF EXISTS `student`;CREATE TABLE `student`(    `id`           bigint(21) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号',    `name`         varchar(20) DEFAULT NULL COMMENT '姓名',    `phone`        varchar(20) DEFAULT NULL COMMENT '电话',    `email`        varchar(50) DEFAULT NULL COMMENT '邮箱',    `gender`       tinyint(2)  DEFAULT NULL COMMENT '性别',    `locked`       tinyint(2)  DEFAULT NULL COMMENT '状态(0:正常,1:定)',    `gmt_created`  datetime    DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间',    `gmt_modified` datetime    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的时间',    `is_deleted`   tinyint(2)  DEFAULT 0,    PRIMARY KEY (`id`)) ENGINE = InnoDB  DEFAULT CHARSET = utf8mb4  COLLATE = utf8mb4_0900_ai_ci COMMENT ='学生表';

代码生成

使用Fluent Mybatis代码生成器,生成对应的Entity文件

public class Generator {    static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8";        static final String basePackage = "cn.org.fluent.mybatis.dynamic";        @BeforeAll    static void runDbScript() {        DataSourceCreatorFactory.create("dataSource");    }    @Test    void test() {        FileGenerator.build(Nothing.class);    }    @Tables(                url = url, username = "root", passWord = "password",                basePack = basePackage,                srcDir = "src/main/java",                gmtCreated = "gmt_created", gmtModified = "gmt_modified", logicDeleted = "is_deleted",                tables = @Table(value = {"student"})    )    public static class Nothing {    }}

编译项目,ok,下面我们开始动态SQL构造旅程

在 WHERE 条件中使用动态条件

在mybatis中,if 标签是大家最常使用的。在查询、删除、更新的时候结合 test 属性联合使用。

示例:根据输入的学生信息进行条件检索

  • 当只输入用户名时, 使用用户名进行模糊检索;

  • 当只输入性别时, 使用性别进行完全匹配

  • 当用户名和性别都存在时, 用这两个条件进行查询匹配查询

mybatis动态 SQL写法

<select id="selectByStudentSelective" resultMap="BaseResultMap" parameterType="com.homejim.mybatis.entity.Student">    select    <include refid="Base_Column_List" />    from student    <where>        <if test="name != null and name !=''">          and name like concat('%', #{name}, '%')        </if>        <if test="sex != null">          and sex=#{sex}        </if>    </where></select>

fluent mybatis动态写法

@Repositorypublic class StudentDaoImpl extends StudentBaseDao implements StudentDao {       @Override    public List<StudentEntity> selectByNameOrEmail(String name, Boolean isMale) {        return super.defaultQuery()            .where.name().like(name, If::notBlank)            .and.gender().eq(isMale, If::notNull).end()            .execute(super::listEntity);    }}

FluentMyBatis的实现方式至少有下面的好处

  • 逻辑就在方法实现上,不需要额外维护xml,割裂开来

  • 所有的编码通过IDE智能提示,没有字符串魔法值编码

  • 编译检查,拼写错误能立即发现

测试

@SpringBootTest(classes = AppMain.class)public class StudentDaoImplTest extends Test4J {    @Autowired    StudentDao studentDao;    @DisplayName("只有名字时的查询")    @Test    void selectByNameOrEmail_onlyName() {        studentDao.selectByNameOrEmail("明", null);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE name LIKE ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{"%明%"});    }    @DisplayName("只有性别时的查询")    @Test    void selectByNameOrEmail_onlyGender() {        studentDao.selectByNameOrEmail(null, false);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE gender = ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{false});    }    @DisplayName("姓名和性别同时存在的查询")    @Test    void selectByNameOrEmail_both() {        studentDao.selectByNameOrEmail("明", false);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE name LIKE ? " +                "AND gender = ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{"%明%", false});    }}

在 UPDATE 使用动态更新

只更新有变化的字段, 空值不更新

mybatis xml写法

<update id="updateByPrimaryKeySelective" parameterType="...">    update student    <set>      <if test="name != null">        `name` = #{name,jdbcType=VARCHAR},      </if>      <if test="phone != null">        phone = #{phone,jdbcType=VARCHAR},      </if>      <if test="email != null">        email = #{email,jdbcType=VARCHAR},      </if>      <if test="gender != null">        gender = #{gender,jdbcType=TINYINT},      </if>      <if test="gmtModified != null">        gmt_modified = #{gmtModified,jdbcType=TIMESTAMP},      </if>    </set>    where id = #{id,jdbcType=INTEGER}</update>

fluent mybatis实现

@Repositorypublic class StudentDaoImpl extends StudentBaseDao implements StudentDao {        @Override    public int updateByPrimaryKeySelective(StudentEntity student) {        return super.defaultUpdater()            .update.name().is(student.getName(), If::notBlank)            .set.phone().is(student.getPhone(), If::notBlank)            .set.email().is(student.getEmail(), If::notBlank)            .set.gender().is(student.getGender(), If::notNull)            .end()            .where.id().eq(student.getId()).end()            .execute(super::updateBy);    }    }

测试

@springBootTest(classes = AppMain.class)public class StudentDaoImplTest extends Test4J {    @Autowired    StudentDao studentDao;    @Test    void updateByPrimaryKeySelective() {        StudentEntity student = new StudentEntity()            .setId(1L)            .setName("test")            .setPhone("13866668888");        studentDao.updateByPrimaryKeySelective(student);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "UPDATE student " +                "SET gmt_modified = now(), " +                "name = ?, " +                "phone = ? " +                "WHERE id = ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{"test", "13866668888", 1L});    }}

choose 标签

在mybatis中choose when otherwise 标签可以帮我们实现 if else 的逻辑。

查询条件,假设 name 具有唯一性, 查询一个学生

  • 当 id 有值时, 使用 id 进行查询;

  • 当 id 没有值时, 使用 name 进行查询;

  • 否则返回空

mybatis xml实现

<select id="selectByIdOrName" resultMap="BaseResultMap" parameterType="...">    select    <include refid="Base_Column_List" />    from student    <where>        <choose>          <when test="id != null">            and id=#{id}          </when>          <when test="name != null and name != ''">            and name=#{name}          </when>          <otherwise>            and 1=2          </otherwise>        </choose>    </where></select>

fluent mybatis实现方式

@Repositorypublic class StudentDaoImpl extends StudentBaseDao implements StudentDao {         @Override    public StudentEntity selectByIdOrName(StudentEntity student) {       return super.defaultQuery()           .where.id().eq(student.getId(), If::notNull)           .and.name().eq(student.getName(), name -> isNull(student.getId()) && notBlank(name))           .and.apply("1=2", () -> isNull(student.getId()) && isBlank(student.getName()))           .end()           .execute(super::findOne).orElse(null);    }}

测试

@SpringBootTest(classes = AppMain.class)public class StudentDaoImplTest extends Test4J {    @Autowired    StudentDao studentDao;    @DisplayName("有 ID 则根据 ID 获取")    @Test    void selectByIdOrName_byId() {        StudentEntity student = new StudentEntity();        student.setName("小飞机");        student.setId(1L);        StudentEntity result = studentDao.selectByIdOrName(student);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE id = ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{1L});    }    @DisplayName("没有 ID 则根据 name 获取")    @Test    void selectByIdOrName_byName() {        StudentEntity student = new StudentEntity();        student.setName("小飞机");        student.setId(null);        StudentEntity result = studentDao.selectByIdOrName(student);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE name = ?",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{"小飞机"});    }    @DisplayName("没有 ID 和 name, 返回 null")    @Test    void selectByIdOrName_null() {        StudentEntity student = new StudentEntity();        StudentEntity result = studentDao.selectByIdOrName(student);        // 验证执行的sql语句        db.sqlList().wantFirstSql().eq("" +                "SELECT id, gmt_created, gmt_modified, is_deleted, email, gender, locked, name, phone " +                "FROM student " +                "WHERE 1=2",            StringMode.SameAsSpace);        // 验证sql参数        db.sqlList().wantFirstPara().eqReflect(new Object[]{});    }}

感谢各位的阅读,以上就是“Fluent MyBatis怎么实现动态SQL”的内容了,经过本文的学习后,相信大家对Fluent MyBatis怎么实现动态SQL这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: Fluent MyBatis怎么实现动态SQL

本文链接: https://www.lsjlt.com/news/299660.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Fluent MyBatis怎么实现动态SQL
    这篇文章主要讲解了“Fluent MyBatis怎么实现动态SQL”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Fluent MyBatis怎么实现动态SQL”吧!目录数据准备代码生成在 W...
    99+
    2023-06-20
  • Fluent MyBatis实现动态SQL
    目录数据准备代码生成在 WHERE 条件中使用动态条件在 UPDATE 使用动态更新choose 标签参考MyBatis 令人喜欢的一大特性就是动态 SQL。在使用 ...
    99+
    2022-11-12
  • FluentMybatis怎么实现mybatis动态sql拼装和fluent api语法
    这篇文章主要讲解了“FluentMybatis怎么实现mybatis动态sql拼装和fluent api语法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“FluentMybatis怎么实现m...
    99+
    2023-06-20
  • FluentMybatis实现mybatis动态sql拼装和fluent api语法
    目录开始第一个例子: Hello World新建演示用的数据库结构创建数据库表对应的Entity类运行测试来见证Fluent Mybatis的神奇配置spring bean定义使用J...
    99+
    2022-11-12
  • MyBatis动态SQL怎么实现
    这篇文章主要介绍了MyBatis动态SQL怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MyBatis动态SQL怎么实现文章都会有所收获,下面我们一起来看看吧。mybatis最强大的功能之一便是它的动态...
    99+
    2023-06-30
  • MyBatis中怎么实现动态SQL!
    这篇文章将为大家详细讲解有关MyBatis中怎么实现动态SQL!,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、if标签if是最常用标签,经常用在判断语句...
    99+
    2022-10-18
  • Mybatis中xml的动态sql怎么实现
    这篇文章主要介绍“Mybatis中xml的动态sql怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Mybatis中xml的动态sql怎么实现”文章能帮助大家解决问题。动态SQL简介动态 SQ...
    99+
    2023-07-02
  • Mybatis在注解上怎么实现动态SQL
    本文小编为大家详细介绍“Mybatis在注解上怎么实现动态SQL”,内容详细,步骤清晰,细节处理妥当,希望这篇“Mybatis在注解上怎么实现动态SQL”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。在注解上实现动...
    99+
    2023-07-02
  • MyBatis动态SQL怎么使用
    今天小编给大家分享一下MyBatis动态SQL怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。MyBatis 框架动态...
    99+
    2023-06-29
  • MyBatis中动态SQL及关联查询怎么实现
    小编给大家分享一下MyBatis中动态SQL及关联查询怎么实现,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!序言 MyBatis,大家都知道,半自动的ORM框架,原来叫ibatis,后来好...
    99+
    2022-10-19
  • Mybatis怎么使用ognl表达式实现动态sql
    这篇文章主要为大家展示了“Mybatis怎么使用ognl表达式实现动态sql”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Mybatis怎么使用ognl表达式实现动态sql”这篇文章吧。新建Us...
    99+
    2023-06-15
  • MyBatis注解实现动态SQL问题
    目录MyBatis注解实现动态SQLMyBatis动态拼接 SQL参数最后补充几个知识点总结MyBatis注解实现动态SQL 在 Mybatis 中,使用注解可以很方便的进行sql操...
    99+
    2023-02-07
    MyBatis注解 MyBatis注解实现动态SQL MyBatis动态SQL
  • 怎么分析mybatis的动态SQL
    这期内容当中小编将会给大家带来有关怎么分析mybatis的动态SQL,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、动态SQL:if 语句根据 username 和 sex 来查询数据。如果userna...
    99+
    2023-06-28
  • Mybatis4 之Mybatis动态sql的实现代码
    1.什么是动态SQL 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if...
    99+
    2022-10-18
  • MyBatis深入解读动态SQL的实现
    目录if和wheretrimChooseSetforeachmybatis最强大的功能之一便是它的动态sql能力        借用...
    99+
    2022-11-13
  • Mybatis中xml的动态sql实现示例
    目录动态SQL简介一、#{}与${}区别#{}表示一个占位符,使用占位符可以防止sql注入,二、传递包装类型三、动态sql—类型四、动态sql—详解(一)if...
    99+
    2022-11-13
  • Mybatis在注解上如何实现动态SQL
    目录在注解上实现动态SQL注解的动态语句支持以下注解方式动态sql写法和注意事项判断字符串为空串 用单引号大于等于用小于等于用在注解上实现动态SQL 使用Mybatis注解实现sql...
    99+
    2022-11-13
  • mybatis动态sql实现逻辑代码详解
    目录1.xml文件读取2.xml 文件解析mybatis通过将sql配置xml文件中,通过解析xml动态标签来实现动态sql 如下样例 xml文件 <?xml ve...
    99+
    2022-11-12
  • MyBatis 超详细讲解动态SQL的实现
    目录情景:概述:SQL元素:<if>:<choose>:<where>:<trim>:<set>:<for...
    99+
    2022-11-13
  • MyBatis动态SQL表达式怎么使用
    本篇内容介绍了“MyBatis动态SQL表达式怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!动态 sql 简单来讲就是我们能通过条件...
    99+
    2023-07-04
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作