Annotation to check set of possible values for string column - Hibernate JPA

775 Views Asked by At

How to check only set of possible values for the String column in hibernate.

@Column(name="delivery_type")
private String deliveryType;

I just want to accept only 1 value from these sets of two. ("Pickup" OR "delivery").

other than these values will throw an exception.

1

There are 1 best solutions below

0
Manas On

As suggested by @SternK, one of the ways is to use Enum by creating an Enum (DeliveryType) like below and use that as an attribute in your entity class:

public enum DeliveryType{
    Pickup,
    Delivery
}

@Enumerated(EnumType.STRING)
private DeliveryType deliveryType;

Hibernate by default stores the ordinal value corresponding to the enum value if you do not use @Enumerated(EnumType.STRING) annotation.

The other way is to create a custom annotation for your desired values, which I think is an overwork in this case. But, if you would like to create a custom annotation then please check this doc from hibernate: https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-constraintannotation