简体   繁体   中英

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

Is it possible to map a subclass 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).

您应该在Hibernate参考中查看“ 继承映射 ”以了解继承映射。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM