How to add the first entity of recursive non-null relation?
The trouble occurs when trying to use my default audit guard (EntityListener) for user entities. Hibernate isnt able to insert first user. The example is simplification of situation:
@Entity
class User {
@Id @GeneratedValue
private Long id;
@Basic
private String name;
@ManyToOne(optional=false)
@JoinColumn(nullable=false,updatable=false)
private User createdBy;
// getters & setters
// equals & hashcode are based on name
}
And I have tried something like:
User user = new User();
user.setName( "Some one" );
user.setCreatedBy( user );
Hibernate fails and root exception is:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into
column 'createdby_id', table 'mydb.user'; column does not allow nulls. INSERT fails.
I know several workarounds: insert first entity manually (SQL insert) or set nullable=true. First is just annoying and second is fail point of integrity (custom audit listener & db trigger required). Is there better options? Or, in the other words: is there JPA-only solution?
My platform is: SQL Server 2008 and Hibernate 3.6 as JPA2 provider.
Edit: At first, I was using persist()
. I tried merge()
which could make more intelligent guess but no difference. And I tried CascadeType.MERGE
too.