如果你有这种类型的JPA实体设置有超类和几个子类(见下文),你如何编写一个JPA查询,它将选择每个子类的前3个(按创建日期排序) ?编写两个单独的查询并询问特定的子类工作正常,但如果可能的话,我想将其归结为一个查询。
@MappedSuperclass
public class Parent {
@Temporal(TIMESTAMP)
@Column(name = "created")
private Date created;
...
}
@Entity
@DiscriminatorValue("A")
public class ChildA extends Parent {
...
}
@Entity
@DiscriminatorValue("B")
public class ChildB extends Parent {
...
}
答案 0 :(得分:1)
您不能将@MappedSuperclass用于此用例(JPA Spec):
与实体不同,映射的超类不可查询,也不能查询 作为参数传递给EntityManager或Query操作。
因此,将您的超类转换为抽象实体:
@Entity
@Inheritance(strategy=SINGLE_TABLE)
@NamedQuery(name="queryName", query="SELECT p FROM Parent p ORDER BY p.createdDate DESC, DTYPE(p) ASC")
public abstract class Parent {
@Temporal(TIMESTAMP)
private Calendar createdDate;
}
答案 1 :(得分:0)
要实现继承,可以将@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
与鉴别器列一起使用...
@MappedSuperclass
:" ...指定一个类,其映射信息应用于从其继承的实体......"
请参阅http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#mapping-declaration
执行此操作后,您只需进行SELECT p from Parent p order by p.created
...