I'm using Hibernate 5 and Spring 3.2.4. I'm deigning a User entity in which I want to include a reference to the user that has created the entity - so a self reference. The self reference itself isn't too problematic, but I want to specify the field as non null. Is this possible? How do I create the first entry in the DB if the field is non null as there referenced entity does not already exist?
Ex:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long User.id;
@NotNull
private String username;
private String password;
@NotNull
private User user;
// getters and setters omitted for brevity
}
If I try:
User u = new User();
u.setUsername("username");
u.setCreatedBy(u);
and try to persist u
, I get the following error message:
Caused by: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: com.domain.User.createdBy -> com.domain.User
I understand that Hibernate is complaining that it cannot reference a transient instance (ie: u
), but I cannot persist u
unless I have an non-null User that I can reference. But in an empty DB, there is no such entry.
Is this kind of configuration impossible to do? Or is there a way around this?