【问题标题】:Jpa - join different tables depend by column typeJpa - 连接不同的表取决于列类型
【发布时间】:2014-01-28 14:25:01
【问题描述】:

我有一个问题,我不确定 jpa 是否可行

如果我说表 A

public class A {
  Long id;
  Long type;
  Details details; // can this connect to B or c depends on type?
}

表 B 和表 C 是两个不同的明细表。 (不确定有什么共同点) 我可以将 B 或 C 连接到 A 取决于 A.type 吗?

谢谢

阿隆

编辑:让我试着更准确一些

我有实体

 @Entity     
 @Table(name = "tbl_A")
 public class A implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
private Long id; // seems like spring's jpa has issue hanlde "_"

    /*
     *can i achive some thinglike
     *   if  detailsTableType== 1 use Details as B table
     */


     @OneToOne(mappedBy = "details", cascade = CascadeType.ALL)
     @PrimaryKeyJoinColumn
     private B details;

    /*
     *can i achive some thinglike
     *   if  detailsTableType== 2 use Details as C table
     */

     @OneToOne(mappedBy = "details", cascade = CascadeType.ALL)
     @PrimaryKeyJoinColumn
     private C details; //Details

     /*
      * this field set the from where the join should be 
      */

     private Long detailsTableType;

}

注意 B、C 不一定有任何共同点

编辑 2:

一种可能的解决方案是使用 getter 进行某种破解。意思是: 在 A 中映射所有可能的连接(将它们标记为惰性)并创建一个 getter,它会根据类型知道它应该使用哪个连接。

【问题讨论】:

  • 您真正拥有的是一个类层次结构,其中包含A 的多个子类。一种A 具有B 详细信息对象,另一种具有C 详细信息对象。这就像 hibernate 的 Table-per-sub-class 和 table-per-class-hierarchy 示例的组合。见docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/…

标签: java jpa jpa-2.0 spring-data


【解决方案1】:

我猜您想通过从 A 类继承 B 和 C 类向 A 实例添加一些细节。 我建议您阅读有关继承和鉴别器值/列的文档。

hibernate 的文档中,您将看到如何 - 使用继承的概念和 TABLE_PER_CLASS 策略 - 并描述描述符列(您的类型列)

编辑: 但我建议您使用另一种策略,例如 SINGLE_TABLE_PER_CLASS。请注意,JPA 提供者不必支持 TABLE_PER_CLASS 策略,而且这种特殊的策略会对性能产生影响。

*第二次编辑:* 好的:我建议您对 B 和 C 类使用多态性,因为它们使用共同的东西 => 与基类 A 的链接!

你可以:

Class A
* Member list of DetailsItf

DetailItf (interface)
 | 
AbstractDetail (SINGLE_TABLE_PER_CLASS strategy with discriminator colum ou TABLE_PER_CLASS) implements DetailItf
 |
 |-B inherits from Details
 |-C inherits from Details

然后你必须在你的基类 A 中使用 AbstractDetail 类,例如:

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany( targetEntity=foo.pck.AbstractDetail.class )
private List<DetailsItf> details = new ArrayList<DetailItf>();

在使用上,你应该做一个

B myB = new B();
//  saving myB entity
A myA = new A();
myA.addDetails(myB);
// saving myA

您还应该根据 TYPE() JPQL 特定关键字或在 jpql 中使用 FROM CLASS 进行特定查询,但您必须创建概念证明并验证性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2011-07-16
    相关资源
    最近更新 更多