gpt4 book ai didi

java - 将原生查询重构为 JPQL 查询

转载 作者:行者123 更新时间:2023-12-02 10:43:45 25 4
gpt4 key购买 nike

假设我们有下表,名为“documents”:

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

两个 *date 列是时间戳,而其他列都是字符串(甚至是 id)

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

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

如您所见,这必须用作 native 查询,因为 JPA 不支持 from 子句中的选择查询。现在我必须将此查询转换为 JPQL 查询,以使其独立于数据库。这在某种程度上可能吗?欢迎使用其他方法,例如使用规范或类似的...

最佳答案

您声明您

want to have a database independent query.

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

SQL 语句相当简单,虽然我不会假装了解每种 SQL 方言,但我希望它能够与许多数据库一起工作,很可能与所有相关的数据库一起工作。

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

如果您坚持使用 JPQL,以下方法可能会起作用:

添加一个实体/表 Two,仅包含一列 (id) 和两个条目:12 >.

您可以按如下方式构建查询:

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

关于java - 将原生查询重构为 JPQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52743320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com