mybatis注解动态sql_超全MyBatis动态SQL详解
MyBatis 令人喜歡的一大特性就是動態(tài) SQL。在使用 JDBC 的過程中, 根據(jù)條件進行 SQL 的拼接是很麻煩且很容易出錯的。MyBatis 動態(tài) SQL 的出現(xiàn), 解決了這個麻煩。
MyBatis通過 OGNL 來進行動態(tài) SQL 的使用的。目前, 動態(tài) SQL 支持以下幾種標(biāo)簽:
1 數(shù)據(jù)準(zhǔn)備
為了后面的演示, 創(chuàng)建了一個 Maven 項目 mybatis-dynamic, 創(chuàng)建了對應(yīng)的數(shù)據(jù)庫和表
DROP TABLE IF EXISTS `student`;CREATE TABLE `student` ( `student_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '編號', `name` varchar(20) DEFAULT NULL COMMENT '姓名', `phone` varchar(20) DEFAULT NULL COMMENT '電話', `email` varchar(50) DEFAULT NULL COMMENT '郵箱', `sex` tinyint(4) DEFAULT NULL COMMENT '性別', `locked` tinyint(4) DEFAULT NULL COMMENT '狀態(tài)(0:正常,1:鎖定)', `gmt_created` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '存入數(shù)據(jù)庫的時間', `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的時間', `delete` int(11) DEFAULT NULL, PRIMARY KEY (`student_id`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='學(xué)生表';對應(yīng)的項目結(jié)構(gòu)
2 if 標(biāo)簽
if 標(biāo)簽是我們最常使用的。在查詢、刪除、更新的時候很可能會使用到。必須結(jié)合 test 屬性聯(lián)合使用。
2.1 在 WHERE 條件中使用 if 標(biāo)簽
這是常見的一種現(xiàn)象, 我們在進行按條件查詢的時候, 可能會有多種情況。
2.1.1 查詢條件
根據(jù)輸入的學(xué)生信息進行條件檢索
- 當(dāng)只輸入用戶名時, 使用用戶名進行模糊檢索;
- 當(dāng)只輸入性別時, 使用性別進行完全匹配
- 當(dāng)用戶名和性別都存在時, 用這兩個條件進行查詢匹配查詢
2.1.2 動態(tài) SQL
接口函數(shù)
/** * 根據(jù)輸入的學(xué)生信息進行條件檢索 * 1. 當(dāng)只輸入用戶名時, 使用用戶名進行模糊檢索; * 2. 當(dāng)只輸入郵箱時, 使用性別進行完全匹配 * 3. 當(dāng)用戶名和性別都存在時, 用這兩個條件進行查詢匹配的用 * @param student * @return */ List selectByStudentSelective(Student student);對應(yīng)的動態(tài) SQL
select from student where 1=1 and name like concat('%', #{name}, '%') and sex=#{sex}在此 SQL 語句中, where 1=1 是多條件拼接時的小技巧, 后面的條件查詢就可以都用 and 了。
同時, 我們添加了 if 標(biāo)簽來處理動態(tài) SQL
and name like concat('%', #{name}, '%') and sex=#{sex}此 if 標(biāo)簽的 test 屬性值是一個符合 OGNL 的表達式, 表達式可以是 true 或 false。如果表達式返回的是數(shù)值, 則0為 false, 非 0 為 true;
2.1.3 測試
@Test public void selectByStudent() { SqlSession sqlSession = null; sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); Student search = new Student(); search.setName("明"); System.out.println("只有名字時的查詢"); List studentsByName = studentMapper.selectByStudentSelective(search); for (int i = 0; i < studentsByName.size(); i++) { System.out.println(ToStringBuilder.reflectionToString(studentsByName.get(i), ToStringStyle.MULTI_LINE_STYLE)); } search.setName(null); search.setSex((byte) 1); System.out.println("只有性別時的查詢"); List studentsBySex = studentMapper.selectByStudentSelective(search); for (int i = 0; i < studentsBySex.size(); i++) { System.out.println(ToStringBuilder.reflectionToString(studentsBySex.get(i), ToStringStyle.MULTI_LINE_STYLE)); } System.out.println("姓名和性別同時存在的查詢"); search.setName("明"); List studentsByNameAndSex = studentMapper.selectByStudentSelective(search); for (int i = 0; i < studentsByNameAndSex.size(); i++) { System.out.println(ToStringBuilder.reflectionToString(studentsByNameAndSex.get(i), ToStringStyle.MULTI_LINE_STYLE)); } sqlSession.commit(); sqlSession.close(); }只有名字時的查詢, 發(fā)送的語句和結(jié)果
查詢的條件只發(fā)送了
where 1=1 and name like concat('%', ?, '%')只有性別時的查詢, 發(fā)送的語句和結(jié)果
查詢的條件只發(fā)送了
where 1=1 and sex=?姓名和性別同時存在的查詢, 發(fā)送的語句和結(jié)果
查詢條件
where 1=1 and name like concat('%', ?, '%') and sex=?2.2 在 UPDATE 更新列中使用 if 標(biāo)簽
有時候我們不希望更新所有的字段, 只更新有變化的字段。
2.2.1 更新條件
只更新有變化的字段, 空值不更新。
2.2.1 動態(tài) SQL
接口方法
/** * 更新非空屬性 */ int updateByPrimaryKeySelective(Student record);對應(yīng)的 SQL
update student `name` = #{name,jdbcType=VARCHAR}, phone = #{phone,jdbcType=VARCHAR}, email = #{email,jdbcType=VARCHAR}, sex = #{sex,jdbcType=TINYINT}, locked = #{locked,jdbcType=TINYINT}, gmt_created = #{gmtCreated,jdbcType=TIMESTAMP}, gmt_modified = #{gmtModified,jdbcType=TIMESTAMP}, where student_id = #{studentId,jdbcType=INTEGER}2.2.3 測試
@Test public void updateByStudentSelective() { SqlSession sqlSession = null; sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); Student student = new Student(); student.setStudentId(1); student.setName("明明"); student.setPhone("13838438888"); System.out.println(studentMapper.updateByPrimaryKeySelective(student)); sqlSession.commit(); sqlSession.close(); }結(jié)果如下
2.3 在 INSERT 動態(tài)插入中使用 if 標(biāo)簽
我們插入數(shù)據(jù)庫中的一條記錄, 不是每一個字段都有值的, 而是動態(tài)變化的。在這時候使用 if 標(biāo)簽, 可幫我們解決這個問題。
2.3.1 插入條件
只有非空屬性才插入。
2.3.2 動態(tài)SQL
接口方法
/** * 非空字段才進行插入 */ int insertSelective(Student record);對應(yīng)的SQL
insert into student總結(jié)
以上是生活随笔為你收集整理的mybatis注解动态sql_超全MyBatis动态SQL详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牙周炎会引起口臭吗
- 下一篇: 食用醋的功效与作用、禁忌和食用方法