I need a simple hibernate example of an entity with a one-to-one relationship with another entity where they both share the primary key. I need to only have to save the main entity that is auto-generating its primary key and the other dependent entity is cascade saved automatically. For example:
public class Person {
@Id
@GeneratedValue
@Column(name = "Id")
private Long id;
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
private Name name;
}
public class Name {
@Id
@Column(name = "Id")
private Long id;
@OneToOne
@PrimaryKeyJoinColumn(name = "Id")
private Person person;
@Column
private String first;
@Column
private String last;
}
Person person = new Person();
person.setName(new Name("first", "last"));
session.save(person);
We were able to easily setup those 2 entities. But we have to first save the person and then save the name through hibernate. It's very important that we only have to save person.