电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Fluent MyBatis實現動態SQL

瀏覽:9日期:2023-10-18 11:35:34
目錄數據準備代碼生成在 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'; /** * 生成代碼的package路徑 */ static final String basePackage = 'cn.org.fluent.mybatis.dynamic'; /** * 使用 test/resource/init.sql文件自動初始化測試數據庫 */ @BeforeAll static void runDbScript() {DataSourceCreatorFactory.create('dataSource'); } @Test void test() {FileGenerator.build(Nothing.class); } @Tables(/** 數據庫連接信息 **/url = url, username = 'root', password = 'password',/** Entity類parent package路徑 **/basePack = basePackage,/** Entity代碼源目錄 **/srcDir = 'src/main/java',/** 如果表定義記錄創建,記錄修改,邏輯刪除字段 **/gmtCreated = 'gmt_created', gmtModified = 'gmt_modified', logicDeleted = 'is_deleted',/** 需要生成文件的表 ( 表名稱:對應的Entity名稱 ) **/tables = @Table(value = {'student'}) ) public static class Nothing { }}

編譯項目,ok,下面我們開始動態SQL構造旅程

在 WHERE 條件中使用動態條件

在mybatis中,if 標簽是大家最常使用的。在查詢、刪除、更新的時候結合 test 屬性聯合使用。

示例:根據輸入的學生信息進行條件檢索

當只輸入用戶名時, 使用用戶名進行模糊檢索; 當只輸入性別時, 使用性別進行完全匹配 當用戶名和性別都存在時, 用這兩個條件進行查詢匹配查詢

mybatis動態 SQL寫法

<select 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 { /** * 根據輸入的學生信息進行條件檢索 * 1. 當只輸入用戶名時, 使用用戶名進行模糊檢索; * 2. 當只輸入性別時, 使用性別進行完全匹配 * 3. 當用戶名和性別都存在時, 用這兩個條件進行查詢匹配的用 * * @param name 姓名,模糊匹配 * @param isMale 性別 * @return */ @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 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 { /** * 根據主鍵更新非空屬性 * * @param student * @return */ @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 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 { /** * 1. 當 id 有值時, 使用 id 進行查詢; * 2. 當 id 沒有值時, 使用 name 進行查詢; * 3. 否則返回空 */ @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地址Fluent MyBatis文檔Test4J框架

到此這篇關于Fluent MyBatis實現動態SQL的文章就介紹到這了,更多相關Fluent MyBatis 動態SQL內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Mybatis 數據庫
相關文章:
主站蜘蛛池模板: 工业冷却塔维修厂家_方形不锈钢工业凉水塔维修改造方案-广东康明节能空调有限公司 | 北京网站建设公司_北京网站制作公司_北京网站设计公司-北京爱品特网站建站公司 | 振动筛-交叉筛-螺旋筛-滚轴筛-正弦筛-方形摇摆筛「新乡振动筛厂家」 | 手持式浮游菌采样器-全排二级生物安全柜-浙江孚夏医疗科技有限公司 | 学叉车培训|叉车证报名|叉车查询|叉车证怎么考-工程机械培训网 | 烟气换热器_GGH烟气换热器_空气预热器_高温气气换热器-青岛康景辉 | 打包箱房_集成房屋-山东佳一集成房屋有限公司 | 纳米二氧化硅,白炭黑,阴离子乳化剂-臻丽拾科技 | 耐腐蚀泵,耐腐蚀真空泵,玻璃钢真空泵-淄博华舜耐腐蚀真空泵有限公司 | 一氧化氮泄露报警器,二甲苯浓度超标报警器-郑州汇瑞埔电子技术有限公司 | 防火卷帘门价格-聊城一维工贸特级防火卷帘门厂家▲ | 雨水收集系统厂家-雨水收集利用-模块雨水收集池-徐州博智环保科技有限公司 | 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | WTB5光栅尺-JIE WILL磁栅尺-B60数显表-常州中崴机电科技有限公司 | 温湿度记录纸_圆盘_横河记录纸|霍尼韦尔记录仪-广州汤米斯机电设备有限公司 | 螺旋丝杆升降机-SWL蜗轮-滚珠丝杆升降机厂家-山东明泰传动机械有限公司 | 企小优-企业数字化转型服务商_网络推广_网络推广公司 | 屏蔽泵厂家,化工屏蔽泵_维修-淄博泵业| X光检测仪_食品金属异物检测机_X射线检测设备_微现检测 | SDG吸附剂,SDG酸气吸附剂,干式酸性气体吸收剂生产厂家,超过20年生产使用经验。 - 富莱尔环保设备公司(原名天津市武清县环保设备厂) | 定制液氮罐_小型气相液氮罐_自增压液氮罐_班德液氮罐厂家 | 武汉宣传片制作-视频拍摄-企业宣传片公司-武汉红年影视 | 工业洗衣机_工业洗涤设备_上海力净工业洗衣机厂家-洗涤设备首页 bkzzy在职研究生网 - 在职研究生招生信息咨询平台 | 冷轧机|两肋冷轧机|扁钢冷轧机|倒立式拉丝机|钢筋拔丝机|收线机-巩义市华瑞重工机械制造有限公司 | 无硅导热垫片-碳纤维导热垫片-导热相变材料厂家-东莞市盛元新材料科技有限公司 | 衢州装饰公司|装潢公司|办公楼装修|排屋装修|别墅装修-衢州佳盛装饰 | ET3000双钳形接地电阻测试仪_ZSR10A直流_SXJS-IV智能_SX-9000全自动油介质损耗测试仪-上海康登 | 三佳互联一站式网站建设服务|网站开发|网站设计|网站搭建服务商 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 蜘蛛车-高空作业平台-升降机-高空作业车租赁-臂式伸缩臂叉装车-登高车出租厂家 - 普雷斯特机械设备(北京)有限公司 | 润东方环保空调,冷风机,厂房车间降温设备-20年深圳环保空调生产厂家 | 臻知网大型互动问答社区-你的问题将在这里得到解答!-无锡据风网络科技有限公司 | 淄博不锈钢,淄博不锈钢管,淄博不锈钢板-山东振远合金科技有限公司 | 防爆暖风机_防爆电暖器_防爆电暖风机_防爆电热油汀_南阳市中通智能科技集团有限公司 | 精密模具加工制造 - 富东懿 | 电动不锈钢套筒阀-球面偏置气动钟阀-三通换向阀止回阀-永嘉鸿宇阀门有限公司 | 东莞爱加真空科技有限公司-进口真空镀膜机|真空镀膜设备|Polycold维修厂家 | 挨踢网-大家的导航!| 管理会计网-PCMA初级管理会计,中级管理会计考试网站 | 宁波普瑞思邻苯二甲酸盐检测仪,ROHS2.0检测设备,ROHS2.0测试仪厂家 | 乐泰胶水_loctite_乐泰胶_汉高乐泰授权(中国)总代理-鑫华良供应链 | 水厂污泥地磅|污泥处理地磅厂家|地磅无人值守称重系统升级改造|地磅自动称重系统维修-河南成辉电子科技有限公司 |