在平常的开发中,有时会使用mybatis的逆向工程,来快速的创建类,其中在创建实例的过程中有一个以Example结尾的类,这个类是专门用来对这个单表来查询的类,就相当于,对该单表的增删改查是脱离sql性质的,直接在service层就可以完成(当然这个sql是逆向已经生过的)
例如:
SELECT * FROM frame.student where sex = '女' order by id desc
Controller: 启动入口
package com.zpark.neimin.first.controller;
import com.zpark.neimin.first.model.Student;
import com.zpark.neimin.first.model.StudentExample;
import com.zpark.neimin.first.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping("/example")
@ResponseBody
public List<Student> example() {
// SELECT * FROM frame.student where sex = '女' order by id desc
StudentExample studentExample = new StudentExample();
//根据id 降序排列
studentExample.setOrderByClause("id desc");
StudentExample.Criteria criteria = studentExample.createCriteria();
criteria.andSexEqualTo("女");
// criteria.andRealNameEqualTo()
List<Student> students = studentService.selectByExample(studentExample);
return students;
}
}
StudentServcie:
package com.zpark.neimin.first.service;
import com.zpark.neimin.first.dao.StudentMapper;
import com.zpark.neimin.first.model.Student;
import com.zpark.neimin.first.model.StudentExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public List<Student> selectByExample(StudentExample studentExample) {
return studentMapper.selectByExample(studentExample);
}
}
说明:
Mybatis逆向工程会生成实例及实例对应的example(用于添加条件,相当于where后的部分)
xxxExample example = new xxxExample();
Criteria criteria = example.createCriteria();
方法说明:
// 1.添加升序排列条件,DESC为降序
example.setOrderByClause("字段名ASC")
// 2.去除重复,boolean类型,true为选择不重复的记录
example.setDistinct(false)
// 3.添加字段xxx为null的条件
criteria.andXxxIsNull
// 4.添加字段xxx不为null的条件
criteria.andXxxIsNotNull
// 5.添加xxx字段等于value条件
criteria.andXxxEqualTo(value)
// 6.添加xxx字段不等于value条件
criteria.andXxxNotEqualTo(value)
// 7.添加xxx字段大于value条件
criteria.andXxxGreaterThan(value)
// 8.添加xxx字段大于等于value条件
criteria.andXxxGreaterThanOrEqualTo(value)
// 9.添加xxx字段小于value条件
criteria.andXxxLessThan(value)
// 10.添加xxx字段小于等于value条件
criteria.andXxxLessThanOrEqualTo(value)
// 11.添加xxx字段值在List
criteria.andXxxIn(List)
// 12.不添加xxx字段值在List
criteria.andXxxNotIn(List)
// 13.添加xxx字段值在之间
criteria.andXxxBetween(value1,value2)
// 14.添加xxx字段值不在之间
criteria.andXxxNotBetween(value1,value2)