jpa动态查询与多表联合查询

jpa操做单表时简单明了,省去了sql的拼写,但若是须要多表联查的时候就不行了。spring

1.当jpa须要联表查询的时候 用到@Query注解,自定义sql 其中nativeQuery=true,指定使用原生sql进行查询sql

@Query(value = "select user.* from user left join role   on ( user.role_id=role.id) where  user.sex=?1  and  role.name is not null;", nativeQuery = true)
    List<User> findUserBy(String sex);

上面的sql用到了left join on 那就说明一下其用法,一般状况下,多表查询都会使用select * from a,b where a.xx=b.xx;数据库

left join on +多条件 先利用on 后面进行两表匹配,而后利用where后面的条件进行筛选,最后选出符合条件的结果。less

a left join b on(a.xx=b.xx) where 筛选条件;

2.spring data jpa使用@Query更新实体类ui

用到jpa自定义sql,须要写数据库时 须要加上 @Modifying(clearAutomatically = true).net

@Modifying(clearAutomatically = true)
    @Query("update user set user.name=?1 where id=?2")
    void updateName(String name,Integer id);

@Modifying源码code

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
public @interface Modifying {

	/**
	 * Defines whether we should clear the underlying persistence context after executing the modifying query.
	 * 
	 * @return
	 */
	boolean clearAutomatically() default false;
}

clearAutomatically,默认为false,表示在执行修改查询后是否清除底层持久化上下文对象

执行完modifying query, EntityManager可能会包含过期的数据,由于EntityManager不会自动清除实体。 只有添加clearAutomatically属性,EntityManager才会自动清除实体对象。接口

3.jpa 动态条件查询ci

首先须要实现 JpaSpecificationExecutor<T> 接口

public List<User> queryUserList(User request)
return userRepository.findAll((Specification<User>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (request != null) {
                if (StringUtils.isNotBlank(request.getUserName())) {
                    predicates.add(criteriaBuilder.equal(root.get("userName"), ProcessStatusEnum.fromName(request.getUsername())));
                }
                

                if (request.getCreateDate() != null && request.getCreateDate().isValidated()) {
                    predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("StartDate"), request.getStartDate()));
                    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("EndDate"), request.getEndDate()));
                }
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, new Sort(Sort.Direction.DESC, "id"));}

以上方法调用了 List<T> findAll(@Nullable Specification<T> spec, Sort sort);

相关文章
相关标签/搜索