以下列舉四種方式,可是不止四種哦。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