Hibernate Enumeration Mapping

狂风中的少年 提交于 2020-01-01 20:49:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!