开发者

Is it possible to map a superclass and subclass by OneToOne relationship in Hibernate?

Is it possible to map a subclas开发者_开发知识库s to its superclass by OneToOne relationship base on their primary key properties in Hibernate? How can I implement this?


You can do it with the JOINED inheritance strategy like this:

@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;
  }
}

This way, the id will be both in the cat and the domesticcat table, both as a primary key, and with a foreign key between the two. This gives you a one to one relationship (without using @OneToOne).


You should look at Inheritance Mapping in the Hibernate reference to understand inheritance mapping.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜