簡單介紹:
Criteria,包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關系。
oredCriteria,Example內有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預示的一樣,這個集合中的Criteria是由OR連接的,是邏輯或關系。oredCriteria就是ORed Criteria。
or()方法,會產生一個新的Criteria對象,添加到oredCriteria中,並返回這個Criteria對象,從而可以鏈式表達,為其添加Criterion。
查詢條件1:a=? and (b=? or c=?) 不支持
查詢條件2:(a=? And b=?) or (a=? And c=?) 支持
寫法1:
1 DemoExample example=new DemoExample(); 2 3 DemoExample.Criteria criteria1=example.createCriteria(); 4 criteria1.andAEqualTo(?).andBEqualTo(?); 5 6 DemoExample.Criteria criteria2=example.createCriteria(); 7 criteria2.andAEqualTo(?).andCEqualTo(?); 8 9 example.or(criteria2); 10 11 SqlSession sqlSession = MyBatisUtil.openSession(); 12 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 13 m.countByExample(example); 14 //生成的sql語句 15 select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )
寫法2:
1 DemoExample example=new DemoExample(); 2 3 example.or().andAEqualTo(?).andBEqualTo(?); 4 example.or().andAEqualTo(?).andCEqualTo(?); 5 6 SqlSession sqlSession = MyBatisUtil.openSession(); 7 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 8 m.countByExample(example); 9 //生成的sql語句 10 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文件,新增方法
1 public Criteria andOrDemo(String value){ 2 addCriterion("(b = \""+value+"\" or c = \""+value+"\")"); 3 return (Criteria) this; 4 }
DemoAction.java
1 DemoExample example=new DemoExample(); 2 Criteria criteria = example.createCriteria(); 3 criteria.andAEqualTo(?).andOrDemo(?); 4 5 SqlSession sqlSession = MyBatisUtil.openSession(); 6 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 7 m.countByExample(example); 8 //生成的sql語句 9 select count(*) from demo WHERE ( a = ? and ( b = ? or c = ? ))