Reputation: 3686
I'm trying to do the following
@ManyToOne
@JoinColumn(name="tier_id", columnDefinition = "INT default 1", nullable = false)
public Tier getTier() {
return tier;
}
but while inserting the record I get
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'tier_id' cannot be null
I want default tier_id
to be 1
if it's not set, but it's not working. How can I correctly set this up?
Upvotes: 0
Views: 1920
Reputation: 691635
The default SQL value is only used if the column is not present at all in the insert statement.
But Hibernate doesn't omit columns in insert statements. If you create an entity instance with a null tier, and persist it, you're effectively saying Hibernate that you want to persist an entity with a null tier, and Hibernate explicitely sets the tier_id column to null, since that's what you told it to do.
So, if you want your entity's tier to be the tier with ID 1, then do it explicitely in your application code:
SomeEntity e = new SomeEntity();
e.setTier(em.getReference(Tier.class, 1));
em.persist(e);
Upvotes: 1