简体   繁体   中英

JPA, left outer join on the same table

How can I execute left outer join in JPA with the same table? 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]"

"ON" in the FROM clause (of JPQL) is invalid syntax before JPA2.1, and that is not yet final. Put the "ON" clause in the WHERE maybe, though not identical in significance. Note that some JPA implementations will already offer support for it though (eg DataNucleus JPA does)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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