jpa操作单表时简单明了,省去了sql的拼写,但如果需要多表联查的时候就不行了。
1.当jpa需要联表查询的时候 用到@Query注解,自定义sql 其中nativeQuery=true,指定使用原生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) ListfindUserBy(String sex);
上面的sql用到了left join on 那就说明一下其用法,通常情况下,多表查询都会使用select * from a,b where a.xx=b.xx;
left join on +多条件 先利用on 后面进行两表匹配,然后利用where后面的条件进行筛选,最后选出符合条件的结果。
a left join b on(a.xx=b.xx) where 筛选条件;
2.spring data jpa使用@Query更新实体类
用到jpa自定义sql,需要写数据库时 需要加上 @Modifying(clearAutomatically = true)
@Modifying(clearAutomatically = true) @Query("update user set user.name=?1 where id=?2") void updateName(String name,Integer id);
@Modifying源码
@Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })@Documentedpublic @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 动态条件查询
首先需要实现 JpaSpecificationExecutor<T> 接口
public ListqueryUserList(User request)return userRepository.findAll((Specification ) (root, query, criteriaBuilder) -> { List 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( Specification<T> spec, Sort sort);