Hibernate:将字符串反序列化为值

时间:2014-03-11 16:24:37

标签: java hibernate enums

我在数据库中有一个字符串,对应于枚举的字符串值。我想告诉Hibernate这个字符串应该被视为来自枚举类的值。像调用

之类的东西
 MyEnum.valueOf(stringName);

如何在我的hibernate xml映射文件中执行此操作?

现在我有这个:

<class name="com.example.SomeObject" table="some_object">
    <id name="id" column="id" />
    <property name="someEnum" column="value"/>
</class>

但我不相信这是有效的,我怀疑可能与此堆栈跟踪有关

ERROR 11-03 08:07:54,458 -Servlet.service() for servlet example threw exception
java.io.StreamCorruptedException: invalid stream header: 494E5445
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.hibernate.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:223)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:180)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:211)
at org.hibernate.type.SerializableType.fromBytes(SerializableType.java:105)
at org.hibernate.type.SerializableType.get(SerializableType.java:62)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:184)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:173)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:105)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2124)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1404)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1332)
at org.hibernate.loader.Loader.getRow(Loader.java:1230)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:603)
at org.hibernate.loader.Loader.doQuery(Loader.java:724)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2228)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
at org.hibernate.loader.Loader.list(Loader.java:2120)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)

1 个答案:

答案 0 :(得分:1)

答案:

<property name="someEnum" column="columnName">
    <type name="org.hibernate.type.EnumType">
        <param name="enumClass">com.example.SomeEnum</param>
    </type>
</property>

然后枚举以字符串值输出。