【问题标题】:JPA inheritance - how to select 3 entities of each child type?JPA继承-如何选择每种子类型的3个实体?
【发布时间】:2014-09-22 22:06:55
【问题描述】:

如果您有这种类型的 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 {
    ...
}

【问题讨论】:

    标签: java hibernate jpa mappedsuperclass


    【解决方案1】:

    您不能将@MappedSuperclass 用于此用例(JPA 规范):

    与实体不同,映射的超类不可查询且不得 作为参数传递给 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;
    }
    

    【讨论】:

      【解决方案2】:

      要实现继承,可以将@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这样简单地进行查询...

      【讨论】:

        猜你喜欢
        • 2013-12-04
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2012-09-14
        • 1970-01-01
        • 2013-01-18
        • 2012-11-11
        • 1970-01-01
        相关资源
        最近更新 更多