Hibernate Annotations - IdentifierGenerationException: attempted to assign id from null one-to-one property

While using Hibernate annotations to implement a @OneToOne relationship where the entities are joined by primary key (@PrimaryKeyJoinColumn) I kept encountering a relatively infamous Exception:
IdentifierGenerationException: attempted to assign id from null one-to-one property
I discovered that my issue could easily be resolved by adding "optional=false" to the dependent side of the relation. Here's a brief summary of the relevant related code.
@Entitypublic class Profile implements Serializable {   @OneToOne(mappedBy="profile", optional=false, fetch=FetchType.LAZY)    public Hospital getHospital() {        return hospital;    }    @Id @GeneratedValue(generator="foreign")    @GenericGenerator(name="foreign", strategy = "foreign", parameters={            @Parameter(name="property", value="hospital")    })    public Long getId() {        return this.id;    }}@Entitypublic class Hospital implements Serializable {    @OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)    @PrimaryKeyJoinColumn    public Profile getProfile() {        return profile;    }    @Id @GeneratedValue(strategy=GenerationType.AUTO)    public Long getId() {        return id;    }}
Share Comments