Is there a way to generate a domain for a field that is defined as enum
while generating DDL from the data model?
The default behaviour for fields that are defined as enum
is either EnumType.STRING
or EnumType.ORDINAL
. In this particular case I use @Enumerated(EnumType.STRING)
.
MyEnum.java
public enum MyEnum {
MY_VALUE_1, MY_VALUE_2, MY_VALUE_3
}
MyEntity.java
@javax.persistence.Entity
public class MyEntity {
@javax.persistence.Id
private long id;
@javax.persistence.Enumerated(javax.persistence.EnumType.STRING)
private MyEnum status;
}
This is unfortunately defined as "only" character varying(255)
(I am using PostgreSQL RDBMS).
ALTER TABLE myentity ADD COLUMN status character varying(255);
This of course gives an opportunity to put garbage there that has nothing to do with the actual enum
.
INSERT INTO myentity(id, status) VALUES (1, 'THIS_HAS_NOTHING_TO_DO_WITH_THE_ENUM');
In this place I would like to be able to give a hint to Hibernate to generate a domain with only those values allowed that actually belong to the enumeration.
As a workaround I wanted to generate a check constraint using @Check
annotation. This however regrettably cannot be done dynamically. I wanted to loop through the MyEnum.values()
in order to generate this check so that I do not have to change it at the same time when the enum gets additional values.
public class MyEntity {
@javax.persistence.Id
private long id;
@javax.persistence.Enumerated(javax.persistence.EnumType.STRING)
@org.hibernate.annotations.Check(constraints = String.format("currentclub in %s", PlayerStatus.values()))
private MyEnum status;
}
This of course leads to a syntax error
The value for annotation attribute Check.constraints must be a constant expression.
which is clear to me as the attribute value must be determined at compilation time.
Is there any other way to do it in a clever way?