问题
If I have an entity like this private Boolean test; I can set its default value like this: @Column(columnDefinition = "boolean default false")
But my problem is how can I set a default value for my custom class?
Assume I have a User class, like this:
public class User {
@Id
@GeneratedValue
Long userID;
String eMail;
@OneToOne(fetch = FetchType.LAZY,targetEntity = LoginCredential.class)
@JoinColumn(name = "userID",referencedColumnName = "userID")
@JsonIgnore
private LoginCredential loginCredential;
}
And LoginCredential like this:
public class LoginCredential {
@Id
@GeneratedValue
Long userID;
String eMail;
@OneToOne(mappedBy = "loginCredential", fetch = FetchType.LAZY)
User user;
};
How can I set a default value of User, so that when I create LoginCredential I get a User too.
I tried User user=new User() and setting in the constructor. Both gave me exception.
Exception :
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.mua.cse616.Model.LoginCredential.user -> com.mua.cse616.Model.User
How can I resolve this ?
回答1:
You need to map between your LoginCredential's user field and User class using JPA entity relationships.
Read:
- Multiplicity in Entity Relationships in Oracle's JavaEE 7 tutorial
- Entity Associations in Hibernate user guide
来源:https://stackoverflow.com/questions/57985516/jpa-default-column-value-of-custom-class