博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jpa动态查询与多表联合查询
阅读量:7057 次
发布时间:2019-06-28

本文共 2364 字,大约阅读时间需要 7 分钟。

hot3.png

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)    List
findUserBy(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 List
queryUserList(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);

转载于:https://my.oschina.net/u/2263272/blog/2998764

你可能感兴趣的文章
linux 函数追踪器
查看>>
ubuntu 更换阿里云的源
查看>>
脚本禁言鼠标右键
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
URPF
查看>>
Linux系统的目录结构介绍
查看>>
定制 SWT/RCP 界面:如何编写一个漂亮的 SWT/RCP 界面
查看>>
Linux日志管理详解
查看>>
Linux 实用命令
查看>>
网站制作之网页技巧
查看>>
1672 区间交(贪心)
查看>>
WebService基础介绍
查看>>
jdbc的使用
查看>>
云计算概念--公有云和私有云介绍
查看>>
托管代码
查看>>
Glusterfs hacker guide(三)
查看>>
谈epoll与高性能
查看>>
验证下载文件
查看>>
python输出%
查看>>