【问题标题】:Refactor native query to JPQL query将本机查询重构为 JPQL 查询
【发布时间】:2019-03-15 13:09:00
【问题描述】:

假设我们有下表,命名为“文档”:

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 子句中的选择查询。现在我必须将此查询转换为 JPQL 查询,以使其独立于数据库。这在某种程度上可能吗? 欢迎使用其他方法,例如使用规范或类似方法...

【问题讨论】:

  • @Query(value = "your-native-sql", nativeQuery = true)怎么样?
  • 原生查询不适用于哪个数据库?
  • 这就是我们现在所拥有的。我们希望你替换原生查询机制。
  • 查询在 SQL Server 上运行良好,但我们希望有一个独立于数据库的查询。

标签: java spring-data-jpa jpql nativequery


【解决方案1】:

你说你

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

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

SQL 语句是一个相当简单的语句,虽然我并不假装知道那里的所有 SQL 方言,但我希望它可以与许多数据库一起使用,很可能与所有相关的数据库一起使用。

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

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

添加一个只有一列 (id) 和两个条目的实体/表 Two12

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

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

【讨论】:

  • 我有不止一个这样的查询,在其中一些查询中使用了一个DATEADD,它是特定于 SQL Server 的,但我们已经知道如何克服这个问题。感谢您的回答,我将与同事一起评估此解决方案。
猜你喜欢
  • 2021-02-15
  • 2017-08-29
  • 1970-01-01
  • 2021-10-09
  • 2011-06-12
  • 2013-09-17
  • 2021-04-03
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多