Adding a constraint to a JPA or Hibernate entity column using annotations
I want to have a column for an entity which only accepts one of an enumerated set of values. For example let's say I have a POJO/entity class "Pet" with a String column "petType". I want petType to only allow one of three values: "cat", "dog", or "gorilla". How would I go about annotating the getPetType() method in order to have a database level constraint created which enforces this?
I am allowing Hibernate to create or update my database table at application start up via the Hibernate property "hbm2ddlauto" being set to "update".
I have tried using a parameterized user type in association with the @Type annotation but this doesn't appear to provide any sort of constraint on the database column itself. There doesn't appear to be a way of specifying this sort of constraint in the @Column annotation short of using some SQL with the columnDefinition element, and I'm hesitant to go this route since it seems that whatever I use there will not be cross platform/database independent (开发者_如何学Pythonimportant to me since I run my code in production on Oracle but I do testing locally using HSQLDB and Derby). Maybe what I want to do just can't be done simply using annotations.
Thanks in advance for any insight you can give me on this topic.
Create a enum of type PetType and defined you mapping as
@Enumerated(EnumType.STRING)
That way, strings are stored in the database and your java enum type only accept the 3 values you specify.
精彩评论