Ayelet Ayelet - 2 months ago 37
Java Question

Spring JPA - default value for enum field in enum

We have an entity with an enum field -

, and we want to set a default value for it using JPA annotations -

However, when we save the entity to the DB, the value of this field is
and not . For the boolean field -
the correct default value (
) is saved.

public class Account {

@Column(name = "id")
protected Long id;

@Column(columnDefinition = "boolean default false")
private boolean isLocked;

@Column(length = 32, columnDefinition = "varchar(32) default 'UNKNOWN'")
@Enumerated(value = EnumType.STRING)
private CommunicationStatus emailCommunicationStatus;

PlayerAccount() {

public enum CommunicationStatus {

If we instead use:
@Column(length = 32, columnDefinition = "varchar(32) default 'UNKNOWN'")
we get the following exception on save:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'emailCommunicationStatus' cannot be null

What are we doing wrong? Why does it only work booleans?


What you did is useful whe some SQL code inserts a row without specifying any value for the emailCommunicationStatus column. In that case, the row will have 'UNKNOWN' as value for this column:

insert into account (id, isLocked) values(1, false)

But Hibernate will never do such an insert. It will always pass the actual value of the emailCommunicationStatus field of this entity. So, if you leave it to null, it will explicitely set it to null in the database:

insert into account (id, isLocked, emailCommunicationStatus) values(1, false, null)

What you want is to set the default value of this field:

@Column(length = 32, columnDefinition = "varchar(32) default 'UNKNOWN'")
@Enumerated(value = EnumType.STRING)
private CommunicationStatus emailCommunicationStatus = CommunicationStatus.UNKNOWN;

It works fine with isLocked because the default value of a boolean field is false.