如何持久化具有枚举字段的对象

时间:2010-11-22 16:13:41

标签: java hibernate persistence enumeration

我在我的域模型中使用了枚举,但是当我尝试将对象持久保存到数据库时出现以下错误:

Exception in thread "main" java.lang.ClassCastException: nl.ru.cmbi.pdbeter.core.model.enums.Enum_WhifFunction cannot be cast to java.lang.String
    at org.hibernate.validator.NotEmptyValidator.isValid(NotEmptyValidator.java:36)
    at org.hibernate.validator.ClassValidator.getInvalidValues(ClassValidator.java:386)
    at org.hibernate.validator.ClassValidator.getInvalidValues(ClassValidator.java:352)
    at org.hibernate.validator.event.ValidateEventListener.validate(ValidateEventListener.java:139)
    at org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172)
    at org.hibernate.action.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:142)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:65)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:535)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:527)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:523)
    at nl.ru.cmbi.pdbeter.core.controller.DAO.GenericDAO.makePersistent(GenericDAO.java:73)
    at nl.ru.cmbi.pdbeter.core.controller.DAO.WhifFunctionDAO.getWhifFunctionSet(WhifFunctionDAO.java:36)
    at nl.ru.cmbi.pdbeter.core.controller.DAO.LoggedErrorWhifDAO.updateWhifFunctionSet(LoggedErrorWhifDAO.java:42)
    at nl.ru.cmbi.pdbeter.whifclient.controller.WhifFunctionsUpdater.executeWhifFunctionsByAccessionCode(WhifFunctionsUpdater.java:93)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy31.executeWhifFunctionsByAccessionCode(Unknown Source)
    at nl.ru.cmbi.pdbeter.whifclient.controller.WhifFunctionsExecutor.executeWhifFunctions(WhifFunctionsExecutor.java:26)
    at nl.ru.cmbi.pdbeter.whifclient.controller.WhifClient.updateWhifFunctions(WhifClient.java:22)
    at nl.ru.cmbi.pdbeter.updater.controller.UpdaterMain.start(UpdaterMain.java:65)
    at nl.ru.cmbi.pdbeter.updater.controller.UpdaterMain.main(UpdaterMain.java:44)

这是我的域名模式:

package nl.ru.cmbi.pdbeter.core.model.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToMany;

import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import nl.ru.cmbi.pdbeter.core.model.enums.Enum_WhifFunction;

import org.hibernate.annotations.NaturalId;
import org.hibernate.validator.NotEmpty;

@Entity
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(callSuper = false, of = { "whifFunction" })
@SuppressWarnings("PMD.UnusedPrivateField")
public class WhifFunction extends DomainObject implements Serializable {
    @NaturalId
    @NotEmpty
    @Enumerated(EnumType.STRING)
    private Enum_WhifFunction           whifFunction;

    @ManyToMany(mappedBy = "whifFunctionSet", cascade = CascadeType.ALL)
    private Set<LoggedErrorWhif> loggedErrorWhifSet = new HashSet<LoggedErrorWhif>();

    public WhifFunction(Enum_WhifFunction whifFunction) {
        if (whifFunction == null) {
            throw new IllegalStateException("WhifFunction is null");
        } else {
            this.whifFunction = whifFunction;
        }
    }

    @Override
    public String toString() {
        return whifFunction.toString();
    }
}

为什么@Enumerated注释不起作用,因为我认为它应该有效?如果它按照预期的那样工作,我怎样才能让它按照我现在认为有效的方式工作?或者换句话说:如何持久化具有枚举字段的对象。

修改 感谢所有的答案。 NotEmpty是偶然的,我没有看到它。我不得不做很多映射,所以我复制粘贴了很多东西,但是当我从字符串更改为枚举时,意外忘记删除NotEmpty。下次我会尝试更仔细地查看堆栈跟踪,我完全错过了NotEmptyValidator。

5 个答案:

答案 0 :(得分:4)

问题是验证器不是映射!

at org.hibernate.validator.NotEmptyValidator.isValid(NotEmptyValidator.java:36)

注释@NotEmpty包含@Size(min = 1) 并且@Size仅支持String,Collection,Map和Array。

答案 1 :(得分:2)

我认为如果您将@NotEmpty更改为@NotNull则应该有效。使用String的NotEmpty应该等同于:

string != null && string.trim().length() > 0

@Enumerated与String一起使用时应将Enum_WhifFunction.name()保留为存储的db值,因此相反它应该Enum_WhifFunction.valuOf(storedValue)将字符串值传回给枚举。

问题很可能发生,因为验证者可能会尝试这样做:

Object o = //get field
String toValidate = (String) o; // throws a class cast if o is of type Enum_WhifFunction
return toValidate != null && toValidate.trim().length() > 0;

答案 2 :(得分:1)

  

java.lang.ClassCastException:nl.ru.cmbi.pdbeter.core.model.enums.Enum_WhifFunction无法强制转换为java.lang.String       at org.hibernate.validator.NotEmptyValidator.isValid(NotEmptyValidator.java:36)

@NotEmpty似乎是probelem的源而不是@Enumerated注释......

答案 3 :(得分:0)

查看Mapping enum types with Hibernate Annotations可能会有所帮助。

从示例中看起来你应该:

private Enum_WhifFunction           whifFunction;
@Enumerated(EnumType.STRING)
public Enum_WhifFunction getWhifFunction() {
  return this.whifFunction;
}

答案 4 :(得分:0)

显然无法将Enum_WhifFunction强制转换为String。 你可以发布Enum_WhifFunction代码吗?