Hibernate:如何通过连接字符串来创建 JPQL?
Posted
技术标签:
【中文标题】Hibernate:如何通过连接字符串来创建 JPQL?【英文标题】:Hibernate : how to create JPQL by concatenating strings? 【发布时间】:2021-10-31 06:34:48 【问题描述】:我正在尝试寻找一种连接字符串以创建 JPA 原生查询的方法。目前我有 3 个查询,只是因为有 1 个或 2 个不同的单词。例如:
String queryAsc = select emp.id,role_id from employee left join roles
on roles.id = emp.role_id
where emp.id = :id
order by employee.created_date asc;
String queryDesc = select emp.id,role_id from employee left join roles
on roles.id = emp.role_id
where emp.id = :id
order by employee.created_date desc;
仅仅因为“asc”和“desc”这个词的不同,我不得不用JPA查询写了2个不同的repository方法:
@Query(value = queryAsc,
countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]> findMyEmployeesAsc(@Param("id") String id, Pageable pageable);
@Query(value = queryDesc,
countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]> findMyEmployeesDesc(@Param("id") String id, Pageable pageable);
有没有办法在 JPA 查询中连接两个字符串以避免这种重复?
【问题讨论】:
你应该放弃通过弹簧连接创建请求的想法。关于使用Crinteria API
或 QueryDSL
或 JooQ
以编程方式创建自定义请求的事情。
【参考方案1】:
尝试使用调用方的排序。
if (condition)
obj.findMyEmployees("123",pageableObject , new Sort("employee.created_date "));
else
obj.findMyEmployees("234",pageableObject ,new Sort(Sort.Direction.DESC,"employee.created_date"));
并重写查询如下:
String query= select emp.id,role_id from employee left join roles
on roles.id = emp.role_id
where emp.id = :id;
@Query(value = query,
countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]> findMyEmployees(@Param("id") String id, Pageable pageable, Sort sort);
【讨论】:
感谢您的回复。这并没有给我直接排序,因为排序和分页不能以这种特定方式在这里一起使用。但是,您的回答给了我寻找什么的方向,我最终使用排序选项作为分页对象的一部分,该对象与 JPA 原生查询一起使用。谢谢以上是关于Hibernate:如何通过连接字符串来创建 JPQL?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JPA 和 Hibernate 连接两个不相关的实体