【问题标题】:Is it possible to map a superclass and subclass by OneToOne relationship in Hibernate?是否可以在 Hibernate 中通过 OneToOne 关系映射超类和子类?
【发布时间】:2011-06-30 11:34:43
【问题描述】:

是否可以通过 OneToOne 关系基于 Hibernate 中的主键属性将子类映射到其超类?我该如何实现?

【问题讨论】:

    标签: java hibernate inheritance mapping one-to-one


    【解决方案1】:

    您可以像这样使用 JOINED 继承策略来做到这一点:

    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class Cat implements Serializable {
    
      private int id;
    
      @Id
      @GeneratedValue
      public int getId() { 
        return id;
      }
    
      public void setId(final int id) {
        this.id = id;
      }
    }
    
    @Entity 
    public class DomesticCat extends Cat {
    
      private String name;
    
      public String getName() { 
        return name;
      }
    
      public void setName(final String name) {
        this.name = name;
      }
    }
    

    这样,id 将在catdomesticcat 表中,都作为主键,并且在两者之间有一个外键。这为您提供了一对一的关系(不使用@OneToOne)。

    【讨论】:

    • 在查询父类型时是否可以避免与每个子类连接?
    【解决方案2】:

    您应该查看 Hibernate 参考中的 Inheritance Mapping 以了解继承映射。

    【讨论】:

      猜你喜欢
      • 2011-03-14
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多