这篇文章主要讲解了“Tk.mybatis零sql语句实现动态sql查询的方法有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Tk.mybatis零sql语句实现动态sql查询的方法有哪些”吧!
有时候,查询数据需要根据条件使用动态查询,这时候需要使用动态sql,通常我们会自己写动态sql来实现,比如:
<select id="findStudentByCondition" resultType="com.example.service.entity.Student">
SELECT id, name, score FROM tbl_student
<where>
<if test="score !=null and score > 0">
score > #{score}
</if>
<if test="name !=null and name != ''">
<bind name="pattern" value=" '%' + name + '%' "/>
AND name LIKE #{pattern}
</if>
</where>
ORDER BY score DESc
</select>
这个sql是查询成绩大于90并且名字包含“i”的学生信息。但是有时候又加了一个条件,又要去改sql,改入参,有没有一种方式可以将写动态sql像写代码一样实现呢?如果你有这个想法,推荐你了解一下Tk.mybatis。
1. 使用Example实现
2. 使用Example.createCriteria
3. 使用Example.builder实现
4. 使用WeekendSqls实现
/**
* 第一种:使用example查询
*/
@Test
public void testSelectByExample() {
Example example = new Example(Student.class);
// 设置查询列
example.selectProperties("id","name","score");
// 动态sql
example.and()
.andGreaterThan("score",90)
.andLike("name", "%i%");
// 去重
example.setDistinct(true);
// 排序
example.orderBy("score").desc();
List<Student> students = studentMapper.selectByExample(example);
System.out.println(students);
}
/**
* 第二种:使用example.createCriteria查询
*/
@Test
public void testSelectByExampleCriteria() {
Example example = new Example(Student.class);
// 设置查询列
example.selectProperties("id","name","score");
// 动态查询
example.createCriteria()
.andGreaterThan("score",90)
.andLike("name", "%i%");
// 去重
example.setDistinct(true);
// 排序
example.orderBy("score").desc();
List<Student> students = studentMapper.selectByExample(example);
System.out.println(students);
}
/**
* 第三种:使用Example.builder实现
*/
@Test
public void testSelectByExampleBuilder() {
Example example = Example.builder(Student.class)
// 查询列
.select("id","name","score")
// 动态sql
.where(Sqls.custom()
.andGreaterThan("score",90)
.andLike("name","%i%"))
// 去重
.distinct()
// 排序
.orderByDesc("score")
.build();
List<Student> students = studentMapper.selectByExample(example);
System.out.println(students);
}
/**
* 第四种:使用weekendSqls实现
*/
@Test
public void testSelectByWeekendSqls() {
WeekendSqls<Student> sqls = WeekendSqls.custom();
sqls = sqls
.andGreaterThan(Student::getScore,90)
.andLike(Student::getName,"%i%");
List<Student> sysRoles = studentMapper.selectByExample(Example.builder(Student.class)
.select("id","name","score")
.where(sqls)
.distinct()
.orderByDesc("score")
.build());
System.out.println(sysRoles);
}
感谢各位的阅读,以上就是“Tk.mybatis零sql语句实现动态sql查询的方法有哪些”的内容了,经过本文的学习后,相信大家对Tk.mybatis零sql语句实现动态sql查询的方法有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。