【问题标题】:Selecting all rows for 3 tables using INNER JOIN in JPQL在 JPQL 中使用 INNER JOIN 选择 3 个表的所有行
【发布时间】:2014-07-09 15:24:03
【问题描述】:

我在选择 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?还是应该只使用 Query 而不是 TypedQuery?

谢谢。

【问题讨论】:

  • JPQL 与 SQL 不是同一种语言。选择 * 是错误的。 JOIN Vehicles As v ON h.vehicleID = v.vehicleID 是错误的。 JPQL 使用关联进行连接。 JPQL 查询选择实体别名和/或实体字段。
  • 我现在明白了。我应该首先引用外键字段为我分配别名。感谢您的回复

标签: java sql jpa jpql


【解决方案1】:

感谢此链接:INNER JOIN IN JPQL

例如:

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

h.vehicleID 为 v

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

【讨论】:

  • 如何进行多个内部连接?所以内连接到一个表,然后内连接到另一个表...
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
相关资源
最近更新 更多