Ayelet Ayelet - 15 days ago 19
Java Question

Spring JPA - default value for enum field in enum

We have an entity with an enum field -

emailCommunicationStatus
, and we want to set a default value for it using JPA annotations -
'UNKNOWN'
.

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

@Entity
public class Account {

@Id
@GeneratedValue
@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() {
super();
}
}

public enum CommunicationStatus {
VALID,
INVALID,
DONT_CONTACT,
UNKNOWN;
}


If we instead use:
@Column(length = 32, columnDefinition = "varchar(32) default 'UNKNOWN'")
for
emailCommunicationStatus
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?

Answer

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.