在JPQL中使用INNER JOIN选择3个表的所有行

时间:2014-05-21 06:24:29

标签: java sql jpa jpql

我在选择JPQL中3个表中的所有行时遇到问题。我想将其作为Collection<Object>返回。

protected Collection<Object> getRecords(){
    emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
    em = emf.createEntityManager();

    em.getTransaction().begin();

    TypedQuery<Object> query = em.createQuery("SELECT * FROM Vehiclehistory As h INNER JOIN Vehicles As v ON h.vehicleID = v.vehicleID INNER JOIN Clients As c ON h.clientID = c.clientID",Object.class);
    Collection<Object> list = query.getResultList();

    em.getTransaction().commit();

    return list;
}

显示的错误是:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: An exception occurred while creating  a query in EntityManager: 
Exception Description: Syntax error parsing [SELECT * FROM Vehiclehistory As h INNER JOIN Vehicles As v ON h.vehicleID = v.vehicleID INNER JOIN Clients As c ON h.clientID = c.clientID]. 
[138, 138] A select statement must have a FROM clause.
[7, 7] The left expression is missing from the arithmetic expression.
[9, 138] The right expression is not an arithmetic expression.

是查询吗?我应该使用createQuery还是createNativeQuery?或者我应该只使用查询而不是TypedQuery?

谢谢。

1 个答案:

答案 0 :(得分:0)

感谢此链接:INNER JOIN IN JPQL

例如:

SELECT v.[vehicleinfo] FROM Vehiclehistory AS h INNER JOIN h.vehicleID AS v ON h.vehicleID = v.vehicleID
  

h.vehicleID as v

它只告诉我需要首先引用左表中的外键并给它一个别名,以便我可以轻松地调用它并在 ON 中使用它