5

I am using jpa/hibernate

Country.java

@Column(nullable = false, name = "REGION")
private String region;

@Id
@Column(nullable = false, name = "CODE")
private String Code;

User.java

@Column(nullable = false, name = "NAME")
private String name;

@NaturalId
@ManyToOne
@JoinColumn(name = "COUNTRY")
private Country country;

Is there a way that I can set a default value for a @joinColumn in User.java for country column in hibernate?

banes
  • 123
  • 1
  • 8
  • refer this link http://stackoverflow.com/questions/197045/setting-default-values-for-columns-in-jpa This maybe helpful to you in some way. – Akash Raveendran Oct 05 '16 at 05:00

1 Answers1

1

Is there a way that I can set a default value for a @joinColumn in User.java for country column in hibernate?

You could use columnDefinition field in @JoinColumn but this is database dependent which is not optimal.

The @PrePersist method might be a better solution:

public class User {
    ...
    @PrePersist
    public void prePersist() {
       if (country == null) {
           country = new Country("US");
       }
    }

For other alternatives examples, see this answer: Setting default values for columns in JPA

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
  • In case Country is a column that currently doesn't exist in my DB. So I am not sure how will schema upgrade take place, considering it needs to be @naturalId and non nullable? I was asking this question since I need to update the existing records to default value of country column – banes Oct 05 '16 at 03:44
  • You have a country id or something in your `User` table right @banes? Or is it in a join table? Regardless, the `@PrePersist` should work. – Gray Oct 05 '16 at 14:24