问题
I have a legacy database table that, for simplicity sake looks like:
table address{
varchar line1
varchar line2
varchar line3
varchar(1) deliveryline
}
There is a check constraint on deliveryline
guaranteeing it has the values '1,'2', or '3'
.
This seems like a good candidate for enumeration in hibernate. I have an entity that looks like this representing the Address table:
public class Address{
String line1;
String line2;
String line3;
DeliveryLine deliveryLine;
}
I normally use @Enumerated(EnumType.STRING)
on when mapping enums, but that strategy does not work here. For example:
public enum DeliveryLine { 1,2,3 } This does not compile since the valid values in the database (1,2,3) are not valid Java Identifiers.
Is there a straightforward way to coerce this mapping in hibernate?
回答1:
Look at GenericEnumUserType
described at hibernate.org (Under "Flexible solution")
If you're using Hibernate 4 you'll have to use a modified version as discussed here
回答2:
Since you're locked into a varchar for column type, I think you're looking at a custom UserType. Such as: http://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/types.html#types-custom-ut
来源:https://stackoverflow.com/questions/9099257/hibernate-enumeration-mapping