菜鸟日志:开发中Spring Data JPA 常用的几个语法

6 篇文章 0 订阅

以前学习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关键字查询列表

表格出处:https://www.jianshu.com/p/a52aa45148b9

keywordsampleJPQL snippet
AndfindByLastnameAndFirstname... where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname... where x.lastname = ?1 or x.firstname = ?2
Is、EqualsfindByFirstname、findByFirstnameIs、findByFirstnameEquals... where x.firstname = ?1
BetweenfindByStartDateBetween... where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan... where x.age < ?1
LessThanEqualsfindByAgeLessThanEqual... where x.age <= ?1
GreaterThanfindByAgeGreaterThan... where x.age > ?1
GreaterThanEqualsfindByAgeGreaterThanEquals... where x.age >= ?1
AfterfindByStartAfter... where x.startDate > ?1
BeforefindByStartBefore... where x.startDate < ?1
IsNullfindByAgeIsNull... where x.age is null
IsNotNull,<br />NotNullfindByAge(Is)NotNull... where x.age not null
LikefindByFirstnameLike... where x.firstname like ?1
NotLikefindByFirstnameNotLike... where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith... where x.firstname like ?1(参数增加前缀%)
EndingWithfindByFirstnameEndingWith... where x.firstname like ?1(参数增加后缀%)
ContainingfindByFirstnameContaining... where x.firstname like ?1(参数被%包裹)
OrderByfindByAgeOrderByLastnameDesc... where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot... where x.lastname <> ?1
InfindByAgeIn(Collection<Age> ages)... where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> ages)... where x.age not in ?1
TruefindByActiveTrue()... where x.active = true
FalsefindByActiveFalse()... where x.active = false
IgnorefindByFirstnameIgnoreCase... where UPPER(x.firstname) = UPPER(?1)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值