在我的应用中,我有以下两个实体:
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Commentable implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
protected long createdDate;
...
}
@Entity
public class Announcement extends Commentable implements Serializable {
private int type;
private String title;
@Column(columnDefinition = "MEDIUMTEXT")
private String content;
...
}
当我尝试从Announcement表中获取一些行时,我会在以下行中出现语法错误:
Query q = em.createQuery("SELECT A FROM Announcement A JOIN Commentable C ON A.id = C.id WHERE A.type=:type ORDER BY C.createdDate DESC");
这是堆栈跟踪:
Caused by: Exception [EclipseLink-8023] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query [SELECT A FROM Announcement A JOIN Commentable C ON A.id = C.id WHERE A.type=:type ORDER BY C.createdDate DESC].
Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException
如果你能告诉我这里做错了什么,我将非常感激。
祝你好运, James Tran
答案 0 :(得分:1)
JPQL中没有ON
子句。这不是必需的,因为您只能加入两个在它们之间具有关联的实体,并且关联的映射已经包含了解必须在哪些列上进行连接所必需的必要信息。所以以下就足够了:
SELECT a FROM Announcement a JOIN a.commentable c
WHERE a.type = :type ORDER BY c.createdDate DESC
这假设您在Announcement
和Commentable
之间拥有ToOne关联。
编辑:公告扩展评论。所以你不需要任何加入。 JPA引擎为您进行连接(如果需要连接,具体取决于继承策略):
SELECT a FROM Announcement a WHERE a.type = :type ORDER BY a.createdDate DESC
答案 1 :(得分:1)
如果公告扩展为可评论,则您不应该加入:
select a from Announcement a where a.type = :type order by a.createdDate desc