问题
Suppose we have the following table, named as 'documents':
id | createDate | createBy | updateDate | updateBy
--------------------------------------------------
(various rows here)
the two *date columns are timestamps while the other are all strings (even the id
)
Currently I have the following native query used in a Spring Repository:
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
As you can see, this must be used as a native query since JPA does not support select query in the from
clause. Now I have to convert this query to a JPQL query, in order to make it database independent. Is this possible in some way?
Other approaches are welcome, like using Specification or similar...
回答1:
You state that you
want to have a database independent query.
I do think you might already have one.
The SQL statement is a rather simple one and while I don't pretend to know every SQL dialect out there I'd expect it to work with many databases, quite possibly with all that are relevant.
My primary recommendation is therefore to setup tests to test against all the databases you need to support and check if it works.
If you insist to use JPQL the following might work:
Add an entity/table Two
with just one column (id
) and two entries: 1
and 2
.
You could construct your query as follows:
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.
来源:https://stackoverflow.com/questions/52743320/refactor-native-query-to-jpql-query