Tk.mybatis零sql语句实现动态sql查询的方法(4种)

网友投稿 1292 2022-11-18

Tk.mybatis零sql语句实现动态sql查询的方法(4种)

Tk.mybatis零sql语句实现动态sql查询的方法(4种)

目录实现方式:方式一:使用Example实现方式二:使用example.createCriteria实现方式三:使用Example.builder实现方式四:使用weekendSqls实现

有时候,查询数据需要根据条件使用动态查询,这时候需要使用动态sql,通常我们会自己写动态sql来实现,比如:

SELECT id, name, score FROM tbl_student

score > #{score}

AND name LIKE #{pattern}

ORDER BY score DESc

这个sql是查询成绩大于90并且名字包含“i”的学生信息。但是有时候又加了一个条件,又要去改sql,改入参,有没有一种方式可以将写动态sql像写代码一样实现呢?如果你有这个想法,推荐你了解一下Tk.mybatis。

关于Tk.mybatis的介绍以及如何配置,本文暂不介绍,不了解的请自行百度,本文只介绍如何基于tk.mybatis实现不写sql语句也能实现动态sql查询。

实现方式:

1. 使用Example实现

2. 使用Example.createCriteria

3. 使用Example.builder实现

4. 使用WeekendSqls实现

方式一:使用Example实现

/**

* 第一种:使用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.orderhttp://By("score").desc();

List students = studentMapper.selectByExample(example);

System.out.println(students);

}

方式二:使用example.createCriteria实现

/**

* 第二种:使用example.createCriteria查询

*/

@Test

public void testSelectByExampleCriteria() {

Example example = new Example(Student.class);

// 设置查询列

example.selectProperties("id","name","score");

// 动态查询

example.createCriteria()

.anXrtLDTDIsdGreaterThan("score",90)

.andLike("name", "%i%");

// 去重

example.setDistinct(true);

// 排序

example.orderBy("score").desc();

List students = studentMapper.selectByExample(example);

System.out.println(students);

}

方式三:使用Example.builder实现

/**

* 第三种:使用Example.builder实现

*/

@Test

public void testSelectByExampleBuilder() {

Example example = Example.builder(Student.cXrtLDTDIslass)

// 查询列

.select("id","name","score")

// 动态sql

.where(Sqls.custom()

.andGreaterThan("score",90)

.andLike("name","%i%"))

// 去重

.distinct()

// 排序

.orderByDesc("score")

.build();

List students = studentMapper.selectByExample(example);

System.out.println(students);

}

方式四:使用weekendSqls实现

/**

* 第四种:使用weekendSqls实现

*/

@Test

public void testSelectByWeekendSqls() {

WeekendSqls sqls = WeekendSqls.custom();

sqls = sqls

.andGreaterThan(Student::getScore,90)

.andLike(Student::getName,"%i%");

List sysRoles = studentMapper.selectByExamplehttp://(Example.builder(Student.class)

.select("id","name","score")

.where(sqls)

.distinct()

.orderByDesc("score")

.build());

System.out.println(sysRoles);

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:9 顺序容器
下一篇:2021届秋招哔哩哔哩前端一面面经
相关文章

 发表评论

暂时没有评论,来抢沙发吧~