I have two entities Post and PostDetails that are mapped as OneToOne with shared primary key, optional=false and id generator strategy set as IDENTITY. When I try to persist the Post entity it fails with following exception "org.hibernate.id.IdentifierGenerationException: null id generated for:class com.demo.hibernate.PostDetails". Assuming we have following entities Post and PostDetails mapped as OneToOne with shared primary key, optional=false and id generator strategy set as IDENTITY as below
@Entity
public class Post implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToOne(mappedBy="post", cascade = { CascadeType.ALL }, optional=false)
private PostDetails details;
public long getId() {
return id;
}
public PostDetails getDetails() {
return details;
}
public void addDetails(PostDetails details) {
this.details = details;
details.setPost(this);
}
public void deleteDetails() {
if(details !=null) {
details.setPost(null);
}
this.details = null;
}
}
@Entity
public class PostDetails implements Serializable {
@Id
@Column
private long id;
@OneToOne
@JoinColumn(name="id")
@MapsId
private Post post;
public long getId() {
return id;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
}
When I execute the following test case to save the entities,
@Test
public void persistPost() {
Session session = sf.getCurrentSession();
session.getTransaction().begin();
Post post = new Post();
PostDetails details = new PostDetails();
post.addDetails(details);
session.persist(post);
session.beginTransaction().commit();
}
It fails to save and throws the following exception:
org.hibernate.id.IdentifierGenerationException: null id generated for:class com.demo.hibernate.PostDetails
The same code works if I change the generator strategy to AUTO from IDENTITY or change to optional=true as below.
Changing
@GeneratedValue(strategy = GenerationType.IDENTITY)
to
@GeneratedValue(strategy = GenerationType.AUTO)
OR
Changing
@OneToOne(mappedBy="post", cascade = { CascadeType.ALL }, optional=false)
to
@OneToOne(mappedBy="post", cascade = { CascadeType.ALL }, optional=true)
|