认真看看, 以后写 SQL 就爽多了:MyBatis 动态 SQL
码农突围
共 2553字,需浏览 6分钟
· 2020-08-18
1 数据准备
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 '状态(0:正常,1:锁定)',
`gmt_created` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间',
`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='学生表';
2 if 标签
2.1 在 WHERE 条件中使用 if 标签
2.1.1 查询条件
当只输入用户名时, 使用用户名进行模糊检索; 当只输入性别时, 使用性别进行完全匹配 当用户名和性别都存在时, 用这两个条件进行查询匹配查询
2.1.2 动态 SQL
/**
* 根据输入的学生信息进行条件检索
* 1. 当只输入用户名时, 使用用户名进行模糊检索;
* 2. 当只输入邮箱时, 使用性别进行完全匹配
* 3. 当用户名和性别都存在时, 用这两个条件进行查询匹配的用
* @param student
* @return
*/
ListselectByStudentSelective(Student student);
<if test="name != null and name !=''">
and name like concat('%', #{name}, '%')
if>
<if test="sex != null">
and sex=#{sex}
if>
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("只有名字时的查询");
ListstudentsByName = 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("只有性别时的查询");
ListstudentsBySex = 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("明");
ListstudentsByNameAndSex = 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();
}
where 1=1 and name like concat('%', ?, '%')
where 1=1 and sex=?
where 1=1 and name like concat('%', ?, '%') and sex=?
2.2 在 UPDATE 更新列中使用 if 标签
2.2.1 更新条件
2.2.1 动态 SQL
/**
* 更新非空属性
*/
int updateByPrimaryKeySelective(Student record);
"updateByPrimaryKeySelective" parameterType="com.homejim.mybatis.entity.Student">
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="sex != null">
sex = #{sex,jdbcType=TINYINT},
if>
<if test="locked != null">
locked = #{locked,jdbcType=TINYINT},
if>
<if test="gmtCreated != null">
gmt_created = #{gmtCreated,jdbcType=TIMESTAMP},
if>
<if test="gmtModified != null">
gmt_modified = #{gmtModified,jdbcType=TIMESTAMP},
if>
set>
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();
}
2.3 在 INSERT 动态插入中使用 if 标签
2.3.1 插入条件
2.3.2 动态SQL
/**
* 非空字段才进行插入
*/
int insertSelective(Student record);
"insertSelective" parameterType="com.homejim.mybatis.entity.Student">
insert into student
"(" suffix=")" suffixOverrides=",">
<if test="studentId != null">
student_id,
if>
<if test="name != null">
`name`,
if>
<if test="phone != null">
phone,
if>
<if test="email != null">
email,
if>
<if test="sex != null">
sex,
if>
<if test="locked != null">
locked,
if>
<if test="gmtCreated != null">
gmt_created,
if>
<if test="gmtModified != null">
gmt_modified,
if>
"values (" suffix=")" suffixOverrides=",">
<if test="studentId != null">
#{studentId,jdbcType=INTEGER},
if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
if>
<if test="sex != null">
#{sex,jdbcType=TINYINT},
if>
<if test="locked != null">
#{locked,jdbcType=TINYINT},
if>
<if test="gmtCreated != null">
#{gmtCreated,jdbcType=TIMESTAMP},
if>
<if test="gmtModified != null">
#{gmtModified,jdbcType=TIMESTAMP},
if>
2.3.3 测试
@Test
public void insertByStudentSelective() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("小飞机");
student.setPhone("13838438899");
student.setEmail("xiaofeiji@qq.com");
student.setLocked((byte) 0);
System.out.println(studentMapper.insertSelective(student));
sqlSession.commit();
sqlSession.close();
}
3 choose 标签
3.1 查询条件
当 studen_id 有值时, 使用 studen_id 进行查询; 当 studen_id 没有值时, 使用 name 进行查询; 否则返回空
3.2 动态SQL
/**
* - 当 studen_id 有值时, 使用 studen_id 进行查询;
* - 当 studen_id 没有值时, 使用 name 进行查询;
* - 否则返回空
*/
Student selectByIdOrName(Student record);
3.3 测试
@Test
public void selectByIdOrName() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("小飞机");
student.setStudentId(1);
Student studentById = studentMapper.selectByIdOrName(student);
System.out.println("有 ID 则根据 ID 获取");
System.out.println(ToStringBuilder.reflectionToString(studentById, ToStringStyle.MULTI_LINE_STYLE));
student.setStudentId(null);
Student studentByName = studentMapper.selectByIdOrName(student);
System.out.println("没有 ID 则根据 name 获取");
System.out.println(ToStringBuilder.reflectionToString(studentByName, ToStringStyle.MULTI_LINE_STYLE));
student.setName(null);
Student studentNull = studentMapper.selectByIdOrName(student);
System.out.println("没有 ID 和 name, 返回 null");
Assert.assertNull(studentNull);
sqlSession.commit();
sqlSession.close();
}
4 trim(set、where)
4.1 where
4.1.1 查询条件
当只输入用户名时, 使用用户名进行模糊检索; 当只输入性别时, 使用性别进行完全匹配 当用户名和性别都存在时, 用这两个条件进行查询匹配查询
4.1.2 动态 SQL
当条件都不满足时:此时 SQL 中应该要不能有 where , 否则导致出错 当 if 有条件满足时:SQL 中需要有 where, 且第一个成立的 if 标签下的 and | or 等要去掉
/**
* 根据输入的学生信息进行条件检索
* 1. 当只输入用户名时, 使用用户名进行模糊检索;
* 2. 当只输入邮箱时, 使用性别进行完全匹配
* 3. 当用户名和性别都存在时, 用这两个条件进行查询匹配的用
*/
ListselectByStudentSelectiveWhereTag(Student student);
4.1.3 测试
@Test
public void selectByStudentWhereTag() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student search = new Student();
search.setName("明");
System.out.println("只有名字时的查询");
ListstudentsByName = studentMapper.selectByStudentSelectiveWhereTag(search);
for (int i = 0; i < studentsByName.size(); i++) {
System.out.println(ToStringBuilder.reflectionToString(studentsByName.get(i), ToStringStyle.MULTI_LINE_STYLE));
}
search.setSex((byte) 1);
System.out.println("姓名和性别同时存在的查询");
ListstudentsBySex = studentMapper.selectByStudentSelectiveWhereTag(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(null);
search.setSex(null);
ListstudentsByNameAndSex = studentMapper.selectByStudentSelectiveWhereTag(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();
}
4.2 set
updateByPrimaryKeySelective
没有使用 标签, 那么我们就要想办法处理字段全为空的条件, 字段不为空的条件等。有了这个, 我们只需要写 if 标签即可, 不需要处理类似的问题。4.3 trim
4.3.1 trim 来表示 where
"where" prefixOverrides="AND |OR">
4.3.2 trim 来表示 set
"SET" suffixOverrides=",">
4.3.3 trim 的几个属性
prefix: 当 trim 元素包含有内容时, 增加 prefix 所指定的前缀 prefixOverrides: 当 trim 元素包含有内容时, 去除 prefixOverrides 指定的 前缀 suffix: 当 trim 元素包含有内容时, 增加 suffix 所指定的后缀 suffixOverrides:当 trim 元素包含有内容时, 去除 suffixOverrides 指定的后缀
5 foreach 标签
collection: 必填, 集合/数组/Map的名称. item: 变量名。即从迭代的对象中取出的每一个值 index: 索引的属性名。当迭代的对象为 Map 时, 该值为 Map 中的 Key. open: 循环开头的字符串 close: 循环结束的字符串 separator: 每次循环的分隔符
5.1 在 where 中使用 foreach
5.1.1 查询条件
5.1.2 动态 SQL
/**
* 获取 id 集合中的用户信息
* @param ids
* @return
*/
ListselectByStudentIdList(List ids);
5.1.3 测试
@Test
public void selectByStudentIdList() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Listids = new LinkedList<>();
ids.add(1);
ids.add(3);
Liststudents = studentMapper.selectByStudentIdList(ids);
for (int i = 0; i < students.size(); i++) {
System.out.println(ToStringBuilder.reflectionToString(students.get(i), ToStringStyle.MULTI_LINE_STYLE));
}
sqlSession.commit();
sqlSession.close();
}
5.2 foreach 实现批量插入
5.2.1 动态SQL
/**
* 批量插入学生
*/
int insertList(Liststudents);
"insertList">
insert into student(name, phone, email, sex, locked)
values
"list" item="student" separator=",">
(
#{student.name}, #{student.phone},#{student.email},
#{student.sex},#{student.locked}
)
5.2.2 测试
@Test
public void insertList() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Liststudents = new LinkedList<>();
Student stu1 = new Student();
stu1.setName("批量01");
stu1.setPhone("13888888881");
stu1.setLocked((byte) 0);
stu1.setEmail("13888888881@138.com");
stu1.setSex((byte) 1);
students.add(stu1);
Student stu2 = new Student();
stu2.setName("批量02");
stu2.setPhone("13888888882");
stu2.setLocked((byte) 0);
stu2.setEmail("13888888882@138.com");
stu2.setSex((byte) 0);
students.add(stu2);
System.out.println(studentMapper.insertList(students));
sqlSession.commit();
sqlSession.close();
}
6 bind 标签
selectByStudentSelective
方法中, 有如下<if test="name != null and name !=''">
and name like concat('%', #{name}, '%')
if>
<if test="name != null and name !=''">
<bind name="nameLike" value="'%'+name+'%'"/>
and name like #{nameLike}
if>
---END--- 重磅!码农突围-技术交流群已成立 扫码可添加码农突围助手,可申请加入码农突围大群和细分方向群,细分方向已涵盖:Java、Python、机器学习、大数据、人工智能等群。 一定要备注:开发方向+地点+学校/公司+昵称(如Java开发+上海+拼夕夕+猴子),根据格式备注,可更快被通过且邀请进群 ▲长按加群 推荐阅读
• 我在谷歌,女友在亚马逊,晒出2人总收入,网友:好酸 • 为什么建议大家使用 Linux 开发?爽(外加七个感叹号) • 华科女博士年薪156万入职华为!最新回应:在深圳也难买房… • Mysql,再见吧,select * ! • 他曾经复读才考上三本,如今让华为开出201万年薪(其实还拒绝了360万offer) • 痛惜!才29岁,年轻博士不幸离世 最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。 获取方式:点“在看”,关注公众号并回复 BAT 领取,更多内容陆续奉上。 如有收获,点个在看,诚挚感谢明天见(。・ω・。)ノ♡
评论
阿里的同事,写的代码真 TMD 优雅!
通过这篇文章你将了解到整洁的代码对项目、公司和你的重要性,以及如何书写整洁的代码.通过命名、类、函数、测试这四个章节,使我们的代码变得整洁.1、为什么要保持代码整洁?不整洁的代码随着时间的增加而增加时,生产力会随之降低.导致的结果就是:代码不易扩展或扩展容易引发其他问题程序崩溃加班增加公司成本(加人
Java专栏
1
老爸嘲讽我了,写破代码一年就挣十几万,他在工地带50个工人,一个月光人头费就3万,让我滚回去跟他干!
点击上方 "大数据肌肉猿"关注, 星标一起成长点击下方链接,进入高质量学习交流群今日更新| 1052个转型案例分享-大数据交流群来自:网络,侵删有个网友的父亲是做工程的,天天就嘲笑他,说他天天写着破代码有啥用,一年就拿个十多万的死工资,然后告诉他自己在工地里面带了50个工人,一个月能抽三万
程序源代码
0
真心建议大家搞个香港身份,再不冲就晚了
香港一直有“互联网荒漠”之称,疫情这三年,香港开始大力扶持互联网 科技工程 /IT产业,公布了《香港智慧城市蓝图》。目前规划已经覆盖到交通、医疗、经济、教育、环境等多个方面。目前在智能制造,5G网络、智慧城市等领域人才,通过香港优才计划入境都极具优势。什么是香港优才计划优才计划,全称优秀人才入境计划
公子龙
0
网友发问:事业编一年6万,干35年退休挣200万,程序员一年60万,5年就挣300万,事业编再爽能有程序员干五年退休爽?
上一篇:阿里P9被裁,赔偿82w在职场中,我们不可避免地会面临多样的工作机会和选择。然而,如果我们仅将这些不同的工作机会仅以金钱作为衡量标准,那么这种比较就显得过于肤浅和狭隘。一些人可能会通过直接的数学计算来决定哪个职业道路更有利可图,但这种方法忽视了工作的本质、工作量的大小、职业成长的机会,以及经
开发者全社区
0
我想写几个专栏,欢迎大家投票
大家好,我是章北海前段时间更新了一个专栏,阅读和订阅都极不理想,看起来是没有做好调研啊。准备启动新的专栏更新计划了,我有几个选题,看大家更喜欢哪一个呢?欢迎投票,拜谢!
机器学习算法与Python实战
0
10个高级的 SQL 查询技巧
来源:towardsdatascience.com/ten-advanced-sql-concepts-you-should-know-for-data-science-interviews-4d7015ec74b0👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Jav
小哈学Java
0
只写后台管理的前端要怎么提升自己
大厂技术 高级前端 Node进阶点击上方 程序员成长指北,关注公众号回复1,加入高级Node交流群本人写了五年的后台管理。每次面试前就会头疼,因为写的页面除了表单就是表格。抱怨过苦恼过也后悔过(虽然我现在已经心安理得的摆烂),但是站在现在的时间点
程序员成长指北
1
字节员工:35岁以后被裁员的,后来都走了哪条路?现在2-2,要不要利用最后一年拼命上个岸。
架构师大咖
架构师大咖,打造有价值的架构师交流平台。分享架构师干货、教程、课程、资讯。架构师大咖,每日推送。
公众号该公众号已被封禁在当今竞争激烈的职场环境中,年龄并不总是一个决定性
源码共读
0