以下列举四种方式,可是不止四种哦。git
其中weekend方式须要升级jdk到1.8及以上。github
废话不代码!sql
首先定义数据库表映射类:数据库
public class MybatisDemo { private Long id; private Long count; private String name; public Long getId() { return id; } public Long getCount() { return count; } public String getName() { return name; } // setter…… }
此处省略了数据库表映射和set方法。mybatis
接下来就是实现example查询的几种方式,核心代码以下:app
方式一:普通Example方式(从and方法开始能够实现动态sql拼接)ui
Example example = new Example(CandidateBrandEntity.class); example //.selectProperties("cabId","cabName") .and().andEqualTo("cabDeleted",0) .andLike("cabName","%d%"); // 排序 example.orderBy("cabCreatedTime") /*.desc()*/ .orderBy("cabId").desc(); // 得到结果 List<CandidateBrandEntity> 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拼接)get
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方式,优点:不用输入属性名,避免数据库有变更或输入错误就会出错it
//得到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);
参考内容:https://github.com/abel533/Mapper/wiki/6.example