JpaRepository与JpaSpecificationExecutor

1.JpaRepository支持接口规范方法名查询。意思是如果在接口中定义的查询方法符合它的命名规则,就可以不用写实现,目前支持的关键字如下。

 

Keyword

Sample

JPQL snippet

IsNotNull

findByAgeNotNull

...  where x.age not null

Like

findByNameLike

...  where x.name like ?1

NotLike

findByNameNotLike

...  where x.name not like ?1

StartingWith

findByNameStartingWith

...  where x.name like ?1(parameter bound with appended %)

EndingWith

findByNameEndingWith

...  where x.name like ?1(parameter bound with prepended %)

Containing

findByNameContaining

...  where x.name like ?1(parameter bound wrapped in %)

OrderBy

findByAgeOrderByName

...  where x.age = ?1 order by x.name desc

Not

findByNameNot

...  where x.name <> ?1

In

findByAgeIn

...  where x.age in ?1

NotIn

findByAgeNotIn

...  where x.age not in ?1

True

findByActiveTrue

...  where x.avtive = true

Flase

findByActiveFalse

...  where x.active = false

And 

findByNameAndAge

...  where x.name = ?1 and x.age = ?2

Or

findByNameOrAge

...  where x.name = ?1 or x.age = ?2

Between

findBtAgeBetween

...  where x.age between ?1 and ?2

LessThan

findByAgeLessThan

...  where x.age  <  ?1

GreaterThan

findByAgeGreaterThan

...  where x.age > ?1

After/Before

...

...

IsNull

findByAgeIsNull

...  where x.age is null

2.JpaRepository相关查询功能

a.Spring DataJPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。

b.假如创建如下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除

findBy,然后对剩下的属性进行解析,假设查询实体为Doc。

1:先判断userDepUuid (根据POJO规范,首字母变为小写)是否为查询实体的一个

属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步;

2:从右往左截取第一个大写字母开头的字符串此处为Uuid),然后检查剩下的字符串是

否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,

则重复第二步,继续从右往左截取;最后假设user为查询实体的一个属性;

3:接着处理剩下部分(DepUuid),先判断user所对应的类型是否有depUuid属性,如

果有,则表示该方法最终是根据“Doc.user.depUuid” 的取值进行查询;否则继

续按照步骤2的规则从右往左截取,最终表示根据“Doc.user.dep.uuid” 的值进

行查询。

4:可能会存在一种特殊情况,比如Doc包含一个user的属性,也有一个userDep 属

性,此时会存在混淆。可以明确在属性之间加上"_"以显式表达意图,比如

"findByUser_DepUuid()"或者"findByUserDep_uuid()"

c.特殊的参数: 还可以直接在方法的参数上加入分页或排序的参数,比如:

Page<UserModel>findByName(String name, Pageable pageable);

List<UserModel>findByName(String name, Sort sort);

d.也可以使用JPA的NamedQueries,方法如下:

1:在实体类上使用@NamedQuery,示例如下:

@NamedQuery(name ="UserModel.findByAge",query = "select o from UserModel

o where o.age >=?1")

2:在自己实现的DAO的Repository接口里面定义一个同名的方法,示例如下:

publicList<UserModel> findByAge(int age);

3:然后就可以使用了,Spring会先找是否有同名的NamedQuery,如果有,那么就不

会按照接口定义的方法来解析。

e.还可以使用@Query来指定本地查询,只要设置nativeQuery为true,比如:

@Query(value="select* from tbl_user where name like %?1" ,nativeQuery=true)

publicList<UserModel> findByUuidOrAge(String name);

注意:当前版本的本地查询不支持翻页和动态的排序

f.使用命名化参数,使用@Param即可,比如:

@Query(value="selecto from UserModel o where o.name like %:nn")

publicList<UserModel> findByUuidOrAge(@Param("nn") String name);

g.同样支持更新类的Query语句,添加@Modifying即可,比如:

@Modifying

@Query(value="updateUserModel o set o.name=:newName where o.name like %:nn")

public intfindByUuidOrAge(@Param("nn") String name,@Param("newName")String

newName);

注意:

1:方法的返回值应该是int,表示更新语句所影响的行数

2:在调用的地方必须加事务,没有事务不能正常执行

f.创建查询的顺序

Spring Data JPA在为接口创建代理对象时,如果发现同时存在多种上述

情况可用,它该优先采用哪种策略呢?

<jpa:repositories>提供了query-lookup-strategy 属性,用以指定查

找的顺序。它有如下三个取值:

1:create-if-not-found:如果方法通过@Query指定了查询语句,则使用该语句实现

查询;如果没有,则查找是否定义了符合条件的命名查询,如果找到,则使用该

命名查询;如果两者都没有找到,则通过解析方法名字来创建查询。这是querylookup-

strategy 属性的默认值

2:create:通过解析方法名字来创建查询。即使有符合的命名查询,或者方法通过

@Query指定的查询语句,都将会被忽略

3:use-declared-query:如果方法通过@Query指定了查询语句,则使用该语句实现

查询;如果没有,则查找是否定义了符合条件的命名查询,如果找到,则使用该

命名查询;如果两者都没有找到,则抛出异常



spring data jpa 通过创建方法名来做查询,只能做简单的查询,那如果我们要做复杂一些的查询呢,多条件分页怎么办,这里,spring data jpa为我们提供了JpaSpecificationExecutor接口,只要简单实现toPredicate方法就可以实现复杂的查询

1.首先让我们的接口继承于JpaSpecificationExecutor

public interface TaskDao extends JpaSpecificationExecutor<Task>{

}
  • 1
  • 2
  • 3

2.JpaSpecificationExecutor提供了以下接口

public interface JpaSpecificationExecutor<T> {

    T findOne(Specification<T> spec);

    List<T> findAll(Specification<T> spec);

    Page<T> findAll(Specification<T> spec, Pageable pageable);

    List<T> findAll(Specification<T> spec, Sort sort);

    long count(Specification<T> spec);
}

其中Specification就是需要我们传进去的参数,它是一个接口


public interface Specification<T> {

    Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);
}

提供唯一的一个方法toPredicate,我们只要按照JPA 2.0 criteria api写好查询条件就可以了,关于JPA 2.0 criteria api的介绍和使用,欢迎参考 
http://blog.csdn.net/dracotianlong/article/details/28445725 
http://developer.51cto.com/art/200911/162722.htm

2.接下来我们在service bean

@Service
public class TaskService {

    @Autowired TaskDao taskDao ;


    /**
     * 复杂查询测试
     * @param page
     * @param size
     * @return
     */
    public Page<Task> findBySepc(int page, int size){

        PageRequest pageReq = this.buildPageRequest(page, size);
        Page<Task> tasks = this.taskDao.findAll(new MySpec(), pageReq);

        return tasks;

    }

     /**
      * 建立分页排序请求 
      * @param page
      * @param size
      * @return
      */
     private PageRequest buildPageRequest(int page, int size) {
           Sort sort = new Sort(Direction.DESC,"createTime");
           return new PageRequest(page,size, sort);
     }

    /**
     * 建立查询条件
     * @author liuxg
     * @date 2016年3月30日 下午2:04:39
     */
    private class MySpec implements Specification<Task>{

        @Override
        public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

     //1.混合条件查询
          /*Path<String> exp1 = root.get("taskName");
            Path<Date>  exp2 = root.get("createTime");
            Path<String> exp3 = root.get("taskDetail");
            Predicate predicate = cb.and(cb.like(exp1, "%taskName%"),cb.lessThan(exp2, new Date()));
            return cb.or(predicate,cb.equal(exp3, "kkk"));

            类似的sql语句为:
            Hibernate: 
                select
                    count(task0_.id) as col_0_0_ 
                from
                    tb_task task0_ 
                where
                    (
                        task0_.task_name like ?
                    ) 
                    and task0_.create_time<? 
                    or task0_.task_detail=?
            */

    //2.多表查询
        /*Join<Task,Project> join = root.join("project", JoinType.INNER);
            Path<String> exp4 = join.get("projectName");
            return cb.like(exp4, "%projectName%");

            Hibernate: 
            select
                count(task0_.id) as col_0_0_ 
            from
                tb_task task0_ 
            inner join
                tb_project project1_ 
                    on task0_.project_id=project1_.id 
            where
                project1_.project_name like ?*/ 
           return null ;  
        }
    }
}

3.实体类task代码如下

@Entity
@Table(name = "tb_task")
public class Task {

    private Long id ;
    private String taskName ;
    private Date createTime ;
    private Project project;
    private String taskDetail ;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "task_name")
    public String getTaskName() {
        return taskName;
    }
    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    @Column(name = "create_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }


    @Column(name = "task_detail")
    public String getTaskDetail() {
        return taskDetail;
    }
    public void setTaskDetail(String taskDetail) {
        this.taskDetail = taskDetail;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "project_id")
    public Project getProject() {
        return project;
    }
    public void setProject(Project project) {
        this.project = project;
    }

}

通过重写toPredicate方法,返回一个查询 Predicate,spring data jpa会帮我们进行查询。

也许你觉得,每次都要写一个类来实现Specification很麻烦,那或许你可以这么写

public class TaskSpec {

    public static Specification<Task> method1(){

        return new Specification<Task>(){
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return null;
            }

        };
    }

    public static Specification<Task> method2(){

        return new Specification<Task>(){
            @Override
            public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return null;
            }

        };
    }

}

那么用的时候,我们就这么用

Page<Task> tasks = this.taskDao.findAll(TaskSpec.method1(), pageReq);

JpaSpecificationExecutor的介绍就到这里,下次再看看怎么通过写hql或者sql语句来进行查询


猜你喜欢

转载自blog.csdn.net/weixin_39418164/article/details/80320491