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.
精彩评论