有一个要求我应该使用 jpa native 查询(因为 jpa 不支持 timestampdiff 函数)。
另外我应该选择同一张表两次,例如: 我有表:个人、任务等
我使用的 native 查询是:“select emp.name, tsk.name, app.name, from Individual emp, Task tsk, Individual app where ...... ”
我想要的预期数据是:“Tom, task1, Jack”,但是给定此 native sql 查询的结果数据是“Jack, task1, Jack”。这意味着 app.name 会覆盖 emp.name。
如果我想获得正确的结果,我必须使用如下查询:“select emp.name, tsk.name, (select app.name from Individual app where xx.id=xx.id), from Individual emp , Task tsk, Individual app where ................"
原生查询代码(获取错误数据):
String nativeSql = "select con.first_name, app.first_name from Individual con, Task tsk, TimeBlock tb, Timesheet ts, Individual app where con.id=ts.owner_id and tb.timesheet_id=ts.id and tb.task_id=tsk.id and tsk.approver_id=app.id";
Query query = entityManager.createNativeQuery(nativeSql);
原生查询代码(可获取正确数据):
String nativeSql = "select con.first_name, (select app.first_name from Individual app where tsk.approver_id=app.id) from Individual con, Task tsk, TimeBlock tb, Timesheet ts, Individual app where con.id=ts.owner_id and tb.timesheet_id=ts.id and tb.task_id=tsk.id and tsk.approver_id=app.id";
Query query = entityManager.createNativeQuery(nativeSql);
jpql查询代码:
String jpql = "select con.firstName, app.firstName from Individual con, Task tsk, TimeBlock tb, Timesheet ts, Individual app where con.id=ts.owner.id and tb.timesheet.id=ts.id and tb.task.id=tsk.id and tsk.approver.id=app.id";
Query query = entityManager.createQuery(jpql);
但有趣的是:
我使用 native sql 查询从 mysql 数据库中搜索(使用命令行、工作台等),结果数据是正确的“Tom、task1、Jack”
如果我使用没有 timestampdiff 特性的 jpql 来满足这个需求,结果数据也是正确的。
刚试了jdbc,如果在jdbc中使用原生sql查询,也能得到正确的数据。
jpa 好像有点问题....
所以任何以前遇到过这种问题并且知道它的本质的人。
感谢您的帮助。
最佳答案
遇到了同样的问题,只是发现您必须为列设置别名才能解决问题。
这给了我错误的结果:
SELECT i.number, taux5_50.vatAmount, taux19_60.vatAmount
FROM Invoice i
LEFT JOIN InvoiceVATLine taux5_50 ON taux5_50.invoice_id=i.id AND taux5_50.rate=5.50
LEFT JOIN InvoiceVATLine taux19_60 ON taux19_60.invoice_id=i.id AND taux19_60.rate=19.60
WHERE ...
这给了我正确的结果:
SELECT i.number, taux5_50.vatAmount AS taux5_50_vatAmount, taux19_60.vatAmount AS taux19_60_vatAmount
FROM Invoice i
LEFT JOIN InvoiceVATLine taux5_50 ON taux5_50.invoice_id=i.id AND taux5_50.rate=5.50
LEFT JOIN InvoiceVATLine taux19_60 ON taux19_60.invoice_id=i.id AND taux19_60.rate=19.60
WHERE ...
关于mysql - jpa原生查询,select同一张表两次问题(hibernate实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10089619/