【发布时间】: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 查询选择实体别名和/或实体字段。
-
我现在明白了。我应该首先引用外键字段为我分配别名。感谢您的回复