Adding a constraint to a column of a JPA or Hibernate object using annotations

I want to have a column for an object that accepts only one of the listed sets of values. For example, suppose I have a POJO / entity class "Pet" with a String column "petType". I want petType to allow only one of three values: cat, dog, or gorilla. How would I try to annotate the getPetType () method to create a database level restriction that provides this?

I allow Hibernate to create or update my database table when the application starts using the Hibernate property "hbm2ddlauto" set to "update".

I tried using a parameterized user type in connection with the @Type annotation, but this does not seem to provide any restrictions for the database column itself. There seems to be no way to specify this type of restriction in the @Column annotation without using any SQL with the columnDefinition element, and I hesitate to go this route, since it seems that everything I use there will not be a cross-platform / independent base data (important to me, since I run my code in production on Oracle, but I test locally using HSQLDB and Derby). Perhaps what I want to do simply cannot be done simply with annotations.

Thanks in advance for any insight you can give me on this subject.

+4
source share
1 answer

Create an enumeration of type PetType and determine what you display as

@Enumerated (EnumType.STRING)

This way the strings are stored in the database, and your java enum type only accepts the values ​​you specify.

+3
source

All Articles