简单介绍:
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 = ? ))
写法1: