以前学习JPA的时候,总觉得JPA太简单了,没什么好学的。现在实习上手开发项目,使用的就是JPA,这才知道什么叫浅水也能淹死人……
目录
一、查询
二、更新
三、删除
四、增加
五、FindBy关键字查询列表
一、查询
JpaRepository支持接口规范方法名查询,意思是如果在接口中定义的查询方法符合它的命名规则,就可以不用写实现。一般查询方法以 find、findBy、read、readBy、get、getBy为前缀,JPA在进行方法解析的时候会把前缀取掉,然后对剩下部分进行解析。常用FindBy关键字的使用方法在文章结尾。
现在给出一个Student的查询例子来让大家能够进一步了解JPA的使用。
1、Repository:
@Autowired
private StudentRepository studentRes ;
public interface StudentRepository extends JpaRepository<Student, String> {
public Student findById(String id);// 根据属性ID查询实体类对象
public Student findByIdAndName(String id,String name);// 根据属性ID和name查询实体类对象
public List<Student> findByNameLike(String name); //根据姓名模糊查询
public Page<Student> findByClassId(String classId, Pageable page); // 根据课程编号进行分页查询
public Page<Student> findByAll(Specification<Student> spec, Pageable page); // 根据课程编号进行分页查询
}
2、Controller:
public ModelAndView index(ModelMap map , HttpServletRequest request ,@Valid final String id , @Valid final String name , @Valid final String classID) {
/*public Student findById(String id);// 根据属性ID查询实体类对象*/
Student student = StudentRes.findById(id);
/*public Student findByIdAndName(String id,String name);// 根据属性ID和name查询实体类对象*/
Page<Student> studentPage = StudentRes.findByIdAndName(String id,String name){
public Predicate toPredicate(Root<StudentEvent> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
list.add( cb.and(cb.equal(root.get("id").as(String.class), id), cb.equal(root.get("name").as(String.class),name)));
return cb.and(list.toArray(p));}
}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "starttime")) ;
/*public List<Student> findByNameLike(String name); //根据姓名模糊查询*/
List<Student> studentList = StudentRes.findByNameLike("%"+name+"%");
/*public Page<Student> findByClassId(String classId, Pageable page); // 根据课程编号进行分页查询*/
Page<Student> studentPage = StudentRes.findByClassId(classId, new PageRequest(5,5));//new PagrRequest(页数,大小)
/*分页信息:页码:前端从1开始,jpa从0开始,做个转换
Pageable pageable = new PageRequest(pageParam.getPage()-1, pageParam.getLimit()); */
/*public Page<Student> findAll(Specification<Student> spec, Pageable pageable); //分页查询*/
Page<Student> page = StudentRes.findAll(new Specification<Student>(){
/** 构造查询条件
* root :Root接口,代表查询的根对象,可以通过root获取实体中的属性
* query :代表一个顶层查询对象,用来自定义查询
* cb :用来构建查询,此对象里有很多条件方法
**/
@Override
public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
if(!StringUtils.isBlank(id)){
list.add(cb.equal(root.get("id").as(String.class), id)) ;
}
if(!StringUtils.isBlank(name)){
list.add(cb.equal(root.get("name").as(String.class),name)));
}
if(!StringUtils.isBlank(classId)){
list.add(cb.like(root.get("classId").as(String.class), "%"+classId+"%")) ;
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}, new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC, "starttime")) ;
}
二、更新
1、根据属性查询到实体类对象
Student student = studentRes.findOne(id);//findOne(Id)查找一个特定的实体
2、设置实体类对象的值,保存
//设置实体类对象属性值
student.setName(name);
//保存
Student studentSave = studentRes.save(student);
JSONObject result = new JSONObject();
if (studentSave!=null){
//success
result.put("code", "200");
result.put("msg", "ok");
result.put("data", map);
}else {
//error
result.put("code", "400");
result.put("msg", "error");
}
三、删除
1、根据属性查询实体类对象(组)
2、根据条件删除某条记录
//删除 选修数学(ID=‘a123’)并且学号为‘123’的学生
List<Student> Cid = studentRes.findByClassId("a123");
for (Student student : Cid) {
if(student.getId().equals("123")){
studentRes.delete(student.getId());
}
}
四、增加
增加一条记录:1、创建实体类对象 2、保存实体类对象
Student s=new Student();
//此处应添加一些数据,特别是主键(不能为空)
s.setId("001");
studentRes.save(s);
JSONObject result = new JSONObject();
if (studentSave!=null){
//success
}else {
//error
}
五、FindBy关键字查询列表
keyword | sample | JPQL snippet |
And | findByLastnameAndFirstname | ... where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | ... where x.lastname = ?1 or x.firstname = ?2 |
Is、Equals | findByFirstname、findByFirstnameIs、findByFirstnameEquals | ... where x.firstname = ?1 |
Between | findByStartDateBetween | ... where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | ... where x.age < ?1 |
LessThanEquals | findByAgeLessThanEqual | ... where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | ... where x.age > ?1 |
GreaterThanEquals | findByAgeGreaterThanEquals | ... where x.age >= ?1 |
After | findByStartAfter | ... where x.startDate > ?1 |
Before | findByStartBefore | ... where x.startDate < ?1 |
IsNull | findByAgeIsNull | ... where x.age is null |
IsNotNull,<br />NotNull | findByAge(Is)NotNull | ... where x.age not null |
Like | findByFirstnameLike | ... where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | ... where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | ... where x.firstname like ?1(参数增加前缀%) |
EndingWith | findByFirstnameEndingWith | ... where x.firstname like ?1(参数增加后缀%) |
Containing | findByFirstnameContaining | ... where x.firstname like ?1(参数被%包裹) |
OrderBy | findByAgeOrderByLastnameDesc | ... where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | ... where x.lastname <> ?1 |
In | findByAgeIn(Collection<Age> ages) | ... where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | ... where x.age not in ?1 |
True | findByActiveTrue() | ... where x.active = true |
False | findByActiveFalse() | ... where x.active = false |
Ignore | findByFirstnameIgnoreCase | ... where UPPER(x.firstname) = UPPER(?1) |