1

在我的应用程序中,我有以下 2 个实体:

@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

如果您能告诉我我在这里做错了什么,我将不胜感激。

最好的问候,詹姆斯·特兰

4

2 回答 2

1

JPQL中没有ON子句。这不是必需的,因为您只能连接两个在它们之间具有关联的实体,并且关联的映射已经包含了解必须在哪些列上进行连接所需的必要信息。因此,以下内容就足够了:

SELECT a FROM Announcement a JOIN a.commentable c
WHERE a.type = :type ORDER BY c.createdDate DESC

这假设您在Announcement和之间有一个 ToOne 关联Commentable

编辑:公告扩展可评论。所以你不需要任何加入。JPA 引擎为您执行连接(如果需要连接,取决于继承策略):

SELECT a FROM Announcement a WHERE a.type = :type ORDER BY a.createdDate DESC
于 2012-05-18T12:20:23.313 回答
1

如果 Announcement 扩展 Commentable,则不需要加入:

select a from Announcement a where a.type = :type order by a.createdDate desc
于 2012-05-18T12:28:41.573 回答