自动生成的MyBatis3样式的代码,会给每个Java对象创建一个额外的Example对象。
这个Example对象主要是用来进行复杂查询的,它里面有一个静态内部类Criteria,可以理解为专门用来保存查询条件的类。
在进行复杂条件查询时,有专门的语句,studentDao为类对应的接口,而example表示存储查询条件即Criteria的对象,对应你要查询的Java对象(Student)的MBG帮你创建的。
List<Student> students = studentDao.selectByExample(example);
当我们要进行复杂条件查询时:
首先创建一个Java对象复杂查询的对象即xxxx对象对应的xxxxExample对象。
StudentExample example = new StudentExample();
然后通过example创建一个Criteria对象:
StudentExample.Criteria criteria2 = example.createCriteria();
Criteria是继承了GeneratedCriteria类,GeneratedCriteria类中有很多判断条件,都是大部分都是and。
如果想要进行or条件的判断,需要使用两个criteria进行组合。
StudentExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("%飞%").andAgeGreaterThan(15L);
StudentExample.Criteria criteria2 = example.createCriteria();
criteria2.andNameLike("%张%");
example.or(criteria2);// 进行组合
最终拼接的sql语句应该是:
select id,name,email,age from student where (name like "%飞%" and age > 15) or (name like "%张%")
同时应该注意Criteria创建的先后顺序:
or中的参数只能是后创建的Criteria对象!!!
否则会出现错误。
下面是or中参数为先创建的Criteria对象,拼接结果为:
select id, name, email, age from student WHERE ( name like ? ) or( name like ? )
底层可能是使用栈来进行Criteria的存储。每次进行or操作,stack执行pop()两次,将第二次pop获得的Criteria和第一次pop得到的Criteria进行拼接(将传入参数和pop两次操作后的Criteria进行拼接):
c1 = createrCriteria();
c2 = createrCriteria();
栈中的顺序:栈底 c1,c2 栈顶
c2 = stack.pop();
c1 = stack.pop();
拼接=====> c1 or c2
如果or中的参数是第一次创建的criteria(即最先入栈的c1),那么执行or操作时
拼接结果:c1 or c1
完整测试代码:
@Test
public void test02(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
// 1、封装查询对象example
StudentExample example = new StudentExample();
// 2、创建一个criteria,criteria就是拼装查询的条件
// 若要进行or条件的判断,可使用critera进行拼接
StudentExample.Criteria criteria = example.createCriteria();
criteria.andNameLike("%飞%").andAgeGreaterThan(15L);
StudentExample.Criteria criteria2 = example.createCriteria();
criteria2.andNameLike("%张%");
// 3、所有的复杂条件都是通过selectByExample进行查询的,传入一个example对象,因为criteria是student一个属性
// 将后面创建的criteria使用or条件拼接:注意只能按顺序来
example.or(criteria2);
List<Student> students = studentDao.selectByExample(example);
for (Student student : students) {
System.out.println(student);
}
}