开发者

Adding a constraint to a JPA or Hibernate entity column using annotations

开发者 https://www.devze.com 2023-01-13 23:19 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号