Maifee Ul Asad
Maifee Ul Asad

Reputation: 4579

jpa default column value of custom class

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 ?

Upvotes: 0

Views: 374

Answers (2)

Maifee Ul Asad
Maifee Ul Asad

Reputation: 4579

In User class:

public static User defaultUser(){
       return new User();// or any user you want to use 
        // just don't use the id field, else it will start populating the user database, then it won't be the same value right.. ;) 
}

Now where you are saving LoginCredential , just put User.defaultUser() there.

It works, I have done this.

Upvotes: 0

Minar Mahmud
Minar Mahmud

Reputation: 2665

You need to map between your LoginCredential's user field and User class using JPA entity relationships.

Read:

Upvotes: 0

Related Questions