【问题标题】:EJB Mapping of @OneToMany relationships with more than one key in mappedBy@OneToMany 关系的 EJB 映射与 mappedBy 中的多个键
【发布时间】:2014-06-24 11:51:43
【问题描述】:

在我的项目中,我想在 mappedBy 属性中使用具有多个键的 @OneToMany 关系。

在我的项目中,我有 IncidentReport 实体和 ReportEntry 实体,下面的映射很简单

@Entity
public class ReportEntry {

...
    @JoinColumn(name = "incident_report", referencedColumnName = "id")
    @ManyToOne
    private IncidentReport incidentReport;

    private int type; // 0,1,2

    ...
} 


@Entity
public class IncidentReport {
    ...    

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "incidentReport")
    private Collection<ReportEntry> reportEntryCollection;


    ...    
}

但理想情况下,我希望在 IncidentReport 类中有 3 个不同的 ReportEntry 集合(每种类型的报告条目一个)。

有没有办法根据 2 个键映射集合,比如 incidentReporttype 的值?

类似这样的:

@Entity
public class IncidentReport {
    ...    

    // Type 0
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "incidentReport", 
                                          mappedBy = "type = 0" )
    private Collection<ReportEntry> reportEntryCollection1;

    // Type 1
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "incidentReport" 
                                          mappedBy = "type = 1" )
    private Collection<ReportEntry> reportEntryCollection1;

    // Type 2
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "incidentReport" 
                                          mappedBy = "type = 2" )
    private Collection<ReportEntry> reportEntryCollection1;


    ...    
}

有没有办法做到这一点?我的后备计划是添加另一个实体来分别映射它们。哪种方法真的很糟糕?

【问题讨论】:

    标签: java jakarta-ee jpa ejb ejb-3.0


    【解决方案1】:

    因为有类型参数,我建议你根据那个参数定义3个不同的实体

    @Entity
    public class Type1ReportEntry extends ReportEntry{}
    
    @Entity
    public class Type2ReportEntry extends ReportEntry{}
    
    @Entity
    public class Type3ReportEntry extends ReportEntry{}
    

    因为就@OneToMany 映射而言,您将无法完成您想要的。

    您不需要定义任何命名查询:

    假设您已经将 EntityManager 资源注入会话 bean,或者从 EntityManagerFactory 创建它

     public ReportEntry getReportEntry(Class<? extends ReportEntry> reportType){
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().
                createQuery();
        cq.select(cq.from(reportType));
        return getEntityManager().createQuery(cq).getResultList();
      }
    

    【讨论】:

    • 我应该如何根据 Type.我应该使用命名查询并在 WHERE 子句中添加 type=1 吗?
    • 如果我必须得到所有类型值为 1 的 ReportEntry 对象。那么我应该如何形成实体。
    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 2017-01-23
    • 2012-02-08
    • 2020-04-15
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    相关资源
    最近更新 更多