方式一:普通Example方式(从and方法开始可以实现动态sql拼接)
Example example = new Example(MybatisDemo.class);
example
//.selectProperties("id","name")
.and().andEqualTo("isDeleted",0)
.andLike("name","%d%");
// 排序
example.orderBy("createTime")
/*.desc()*/
.orderBy("id").desc();
// 获得结果
List<MybatisDemo> brands = brandEntityMapper.selectByExample(example);
方式二:Criteria方式(可使用criteria完成动态sql拼接)
Example example = new Example(MybatisDemo.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("count", 0)
.andLike("name", "%d%");
example.orderBy("count")
//.desc()
.orderBy("name").desc();
List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(example);
方式三:Example.builder 方式(其中where从句中内容可以拿出来进行动态sql拼接)
Example example = Example.builder(MybatisDemo.class)
.select("cabId","cabName")
.where(Sqls.custom().andEqualTo("count", 0)
.andLike("name", "%d%"))
.orderByDesc("count","name")
.build();
List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(example);
方式四:Example.builder + Weekend方式,优势:不用输入属性名,避免数据库有变动或输入错误就会出错
注:weekend方式要求jdk1.8或以上。
//获得seekendsql
WeekendSqls<MybatisDemo> sqls = WeekendSqls.<MybatisDemo>custom();
//可进行动态sql拼接
sqls = sqls.andEqualTo(MybatisDemo::getCount,0).andLike(MybatisDemo::getName,"%d%");
//获得结果
List<MybatisDemo> demos = mybatisDemoMapper.selectByExample(Example.builder(MybatisDemo.class).where(sqls).orderByDesc("count","name").build());
带逻辑分页的查询(逻辑分页,其实是查询了所有数据,只是返回了需要的)
RowBounds bounds = new RowBounds(1,10);
List<MybatisDemo> brands = brandEntityMapper.selectByExampleAndRowBounds(
Example.builder(MybatisDemo.class)
.where(WeekendSqls.<MybatisDemo>custom()
.andEqualTo(MybatisDemo::getCount,0))
.build(),bounds);
参考:tk.mybatis通用mapper指定字段名查询方法,使用Example的查询方法_ipifei的博客-CSDN博客