MyBatis Generator 生成的example 使用 and or 簡單混合查詢
參考博客:https://www.cnblogs.com/kangping/p/6001519.html
簡單介紹:
Example類用於構造復雜的篩選條件
1、Criterion[標准,准則,規范,准據] 條件
Criterion是最基本,最底層的Where條件,用於字段級的篩選,例如:字段 in | not in | like | > | >= | < | <= | is not null | is null 等
實例:某字段【user】,Criterion為【 user is not null】
MyBatis Generator會為每個字段產生如上的Criterion,如果表的字段比較多,產生的Example類會十分龐大。
理論上通過Example類可以構造你想到的任何篩選條件。
注意:但分頁一般不用,它會將數據全部查詢出來,在內存中分頁,查詢效率較慢
public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; }
查詢條件1:a=? and (b=? or c=?) 不支持
查詢條件2:(a=? And b=?) or (a=? And c=?) 支持
寫法一:
DemoExample example=new DemoExample(); DemoExample.Criteria criteria1=example.createCriteria(); criteria1.andAEqualTo(?).andBEqualTo(?); DemoExample.Criteria criteria2=example.createCriteria(); criteria2.andAEqualTo(?).andCEqualTo(?); example.or(criteria2); SqlSession sqlSession = MyBatisUtil.openSession(); DemoMapper m = sqlSession.getMapper(DemoMapper.class); m.countByExample(example);
生成SQL語句:
select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )
寫法二:
DemoExample example=new DemoExample(); example.or().andAEqualTo(?).andBEqualTo(?); example.or().andAEqualTo(?).andCEqualTo(?); SqlSession sqlSession = MyBatisUtil.openSession(); DemoMapper m = sqlSession.getMapper(DemoMapper.class); m.countByExample(example);
生成SQL語句:
select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )
查詢條件3:(a=? and (b=? or c=?)) 支持
假設兩個搜索項,A項搜索,可搜索b,c(bc或關系),B項搜索可搜索a,B項搜索與A項搜索是與關系。
修改DemoExample.java文件,新增方法:
public Criteria andOrDemo(String value){ addCriterion("(b = \""+value+"\" or c = \""+value+"\")"); return (Criteria) this; }
DemoAction.java
DemoExample example=new DemoExample(); Criteria criteria = example.createCriteria(); criteria.andAEqualTo(?).andOrDemo(?); SqlSession sqlSession = MyBatisUtil.openSession(); DemoMapper m = sqlSession.getMapper(DemoMapper.class); m.countByExample(example); //生成的sql語句 select count(*) from demo WHERE ( a = ? and ( b = ? or c = ? ))
項目應用:
Step1:應用generatorConfig.xml自動根據表字段生成PO類,mapper接口與mapper.xml映射文件
Step2:創建Controller類,Service接口及Service實現類,Controller調用Service,service實現類核心代碼:
public String getTraceaccountByPin(String pin) { UserAccountExample example = new UserAccountExample(); UserAccountExample.Criteria criteria = example.createCriteria(); criteria.andAccountEqualTo(pin); criteria.andDelFlagEqualTo(0); criteria.andAccountstateEqualTo(1); List<UserAccount> accounts = mapper.selectByExample(example); if (accounts.size() > 0 && accounts.get(0) != null) { return accounts.get(0).getTraceaccount(); } return null; }
說明:在generatorConfig.xml自動生成的mapper.xml文件的SQL中自動追加條件 and account=? and delFlag=? and accountsState=?
其他
Example類的distinct字段用於指定DISTINCT查詢。
orderByClause字段用於指定ORDER BY條件,這個條件沒有構造方法,直接通過傳遞字符串值指定。