简体   繁体   English

JPA,同一表上的左外部联接

[英]JPA, left outer join on the same table

How can I execute left outer join in JPA with the same table? 如何在JPA中使用同一表执行左外部联接? When I try this: 当我尝试这个:

sql.append("SELECT e1 FROM ");
sql.append(getPersistentClass().getName());
sql.append(" e1 LEFT OUTER JOIN ");
sql.append(getPersistentClass().getName());
sql.append(" e2 ON e1.username = e2.username AND e1.radacctid < e2.radacctid ");
sql.append("WHERE e2.radacctid IS NULL ");
sql.append("AND e1.acctstoptime IS NOT NULL ");
sql.append("AND DATEDIFF(NOW(), e1.acctstoptime) > ?1");

I get error: "unexpected token: ON near line 1, column 122 [SELECT e1 FROM com.homersoft.wh.db.entity.radius.RadAcct e1 LEFT OUTER JOIN com.homersoft.wh.db.entity.radius.RadAcct e2 ON e1.username = e2.username AND e1.radacctid < e2.radacctid WHERE e2.radacctid IS NULL AND e1.acctstoptime IS NOT NULL AND DATEDIFF(NOW(), e1.acctstoptime) > ?1]" 我收到错误消息:“意外令牌:在第1行第122列附近[从com.homersoft.wh.db.entity.radius.RadAcct e1中选择e1左外部联接com.homersoft.wh.db.entity.radius.RadAcct e2在e1.username = e2.username和e1.radacctid <e2.radacctid上,e2.radacctid为NULL并且e1.acctstoptime不是NULL并且DATEDIFF(NOW(),e1.acctstoptime)>?1]“

"ON" in the FROM clause (of JPQL) is invalid syntax before JPA2.1, and that is not yet final. (JPQL的)FROM子句中的“ ON”在JPA2.1之前是无效的语法,并且尚未最终确定。 Put the "ON" clause in the WHERE maybe, though not identical in significance. 可能将“ ON”子句放在WHERE中,尽管含义并不完全相同。 Note that some JPA implementations will already offer support for it though (eg DataNucleus JPA does) 请注意,尽管有些JPA实现已经提供了支持(例如, DataNucleus JPA确实提供了支持)

I have changed the query like that: 我已经改变了这样的查询:

    StringBuilder sql = new StringBuilder();
    sql.append("SELECT e1 FROM ");
    sql.append(getPersistentClass().getName());
    sql.append(" e1 ");
    sql.append("WHERE e1.id = (");

    sql.append(" SELECT MAX(e2.id) FROM ");
    sql.append(getPersistentClass().getName());
    sql.append(" e2 WHERE e1.userName = e2.userName)");

    sql.append("AND e1.stopTime IS NOT NULL ");
    sql.append("AND e1.stopTime < ?1");

Of course it is slower than the original one. 当然,它比原始的慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM