将本地查询重构为JPQL查询

时间:2018-10-10 15:06:38

标签: java spring-data-jpa jpql nativequery

假设我们有一个名为“文档”的下表:

id | createDate | createBy | updateDate | updateBy
--------------------------------------------------
(various rows here)

两个* date列是时间戳记,而另一个都是字符串(甚至是id

目前,我在Spring存储库中使用了以下本机查询:

select COUNT(distinct(u.user_working_total)) 
     from
(
    select distinct(createBy) user_working_total
    from documents
    where createDate >= :startDate and 
    createDate <= :endDate

    union

    select distinct(updateBy) user_working_total
    from documents
    where updateDate >= :startDate and 
    updateDate <= :endDate
) as u

如您所见,由于JPA在from子句中不支持select查询,因此必须将其用作本机查询。现在,我必须将此查询转换为JPQL查询,以使其独立于数据库。这有可能吗? 欢迎使用其他方法,例如使用“规范”或类似方法...

1 个答案:

答案 0 :(得分:1)

您声明自己

  

想要有一个独立于数据库的查询。

我认为您可能已经有一个。

SQL语句很简单,虽然我不假装不了解其中的每个SQL方言,但我希望它可以与许多数据库一起使用,很可能与所有相关的数据库都可以使用。

因此,我的主要建议是设置测试,以针对需要支持的所有数据库进行测试,并检查其是否有效。

如果您坚持使用JPQL,则可能会起作用:

添加仅具有一列(Two)和两个条目的实体/表id12

您可以按以下方式构造查询:

select
    count(distinct coalesce(t.id, 1, d.createDate, 2, d.updateDate))
from Documents d, Two t
where (t.id = 1
    and d.createDate >= :startDate 
    and d.createDate <= :endDate)
or (t.id = 2
    and d.updateDate >= :startDate 
    and d.updateDate <= :endDate)

Not sure if count( function(x)) is supported or not