天天看點

MyBatis - MyBatis Generator 生成的example and 和or的差別

MyBatis - MyBatis Generator 生成的example and 和or的差別

簡單介紹:

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:
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 = ? )
           
寫法2:
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 = ? ))
           

轉載: MyBatis - MyBatis Generator 生成的example 如何使用 and or 簡單混合查詢

繼續閱讀