Java中mybatis關于example類的使用詳解
這幾天剛接觸example,很多內容都是破碎的,寫一篇博文加深理解。
一、什么是example類
mybatis-generator會為每個字段產生如上的Criterion,如果表的字段比較多,產生的Example類會十分龐大。理論上通過example類可以構造你想到的任何篩選條件。在mybatis-generator中加以配置,配置數據表的生成操作就可以自動生成example了。具體配置可以參考MBG有關配置。 下面是mybatis自動生成example的使用。
二、了解example成員變量
//升序還是降序 //參數格式:字段+空格+asc(desc) protected String orderByClause; //去除重復 //true是選擇不重復記錄 protected boolean distinct; //自定義查詢條件 //Criteria的集合,集合中對象是由or連接 protected List<Criteria> oredCriteria; //內部類Criteria包含一個Cretiron的集合, //每一個Criteria對象內包含的Cretiron之間 //是由AND連接的 public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } //是mybatis中逆向工程中的代碼模型 protected abstract static class GeneratedCriteria {…..} //是最基本,最底層的Where條件,用于字段級的篩選 public static class Criterion {……}
三、example使用前的準備
比如我的example是根據user表生成的,UserMapper屬于dao層,UserMapper.xml是對應的映射文件 UserMapper接口:
long countByExample(CompetingStoreExample example);List<CompetingStore> selectByExample(CompetingStoreExample example);
在我們的測試類里:
UserExample example = new UserExample(); UserExample.Criteria criteria = example.createCriteria();
四、查詢用戶數量
long count = UserMapper.countByExample(example);
類似于:select count(*) from user
五、where條件查詢或多條件查詢
example.setOrderByClause('age asc');//升序 example.setDistinct(false);//不去重 if(!StringUtils.isNotBlank(user.getName())){ Criteria.andNameEqualTo(user.getName()); } if(!StringUtils.isNotBlank(user.getSex())){ Criteria.andSexEqualTo(user.getSex()); } List<User> userList=userMapper.selectByExample(example);
類似于:select * from user where name={#user.name} and sex={#user.sex} order by age asc;
UserExample.Criteria criteria1 = example.createCriteria(); UserExample.Criteria criteria2 = example.createCriteria(); if(!StringUtils.isNotBlank(user.getName())){ Criteria1.andNameEqualTo(user.getName()); } if(!StringUtils.isNotBlank(user.getSex())){ Criteria2.andSexEqualTo(user.getSex()); } Example.or(criteria2); List<User> userList=userMapper.selectByExample(example);
類似于:select * from user where name={#user.name} or sex={#user.sex} ;
六、模糊查詢
if(!StringUtils.isNotBlank(user.getName())){ criteria.andNameLIke(‘%’+name+’%’); } List<User> userList=userMapper.selectByExample(example);
類似于:
select * from user where name like %{#user.name}%
七、分頁查詢
int start = (currentPage - 1) * rows;//分頁查詢中的一頁數量example.setPageSize(rows); //開始查詢的位置example.setStartRow(start);List<User> userList=userMapper.selectByExample(example);
類似于:
select * from user limit start to rows
到此這篇關于Java中mybatis中關于example類的使用詳解的文章就介紹到這了,更多相關Java mybatis中example類內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
