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);