5

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 (important 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.

1
  • Same problem here. Surprising that there doesn't seem to be a way to this? Commented Apr 18, 2011 at 11:07

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works fine at the Java/Hibernate level, but the constraint on the database column is not created when Hibernate creates/updates the schema, so I end up with an unconstrained string column in the database table. This is problematic in case data is inserted into the table outside of my Hibernate code, in that a value can be inserted into the column which is not one of the enumerated values I've specified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.