Hibernate异常:枚举类的未知名称值 [英] Hibernate Exception: Unknown name value for enum class

查看:864
本文介绍了Hibernate异常:枚举类的未知名称值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试从DB检索记录时,我可以获取枚举类的未知名称值。使用jsf 2.0,jpa。

Im getting Unknown name value for enum class when trying to retrieve records from DB. Using jsf 2.0, jpa.

我的数据库中可能的值为'F'或'J'

The possible values in my DB are 'F' or 'J'

枚举:

public enum TipoPessoa {

    FISICA ("F", "Física"),
    JURIDICA ("J", "Jurídica");

    private final String id;
    private final String descricao;

    private TipoPessoa(String id, String descricao){
        this.id = id;
        this.descricao = descricao;
    }

    public String getId() {
        return id;
    }

    public String getDescricao(){
        return descricao;
    }
}

实体: p>

entity :

@Column(nullable=false, length=1)
private TipoPessoa tipoPessoa;

public TipoPessoa getTipoPessoa() {
    return tipoPessoa;
}

public void setTipoPessoa(TipoPessoa tipoPessoa) {
    this.tipoPessoa = tipoPessoa;
}

当我尝试从DB中读取记录时,我收到错误

When I try to read the records from DB I got the error

请问这个问题可以帮我吗?谢谢

Would you please help me on this issue ? thanks

堆栈跟踪

javax.servlet.ServletException:未知的名称值对于枚举类br.com.aaa.xxx.entidade.TipoPessoa:F
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
br.com.aaa.filtro.FiltroEncode。 doFilter(FiltroEncode.java:26)
根本原因

javax.servlet.ServletException: Unknown name value for enum class br.com.aaa.xxx.entidade.TipoPessoa: F javax.faces.webapp.FacesServlet.service(FacesServlet.java:606) br.com.aaa.filtro.FiltroEncode.doFilter(FiltroEncode.java:26) root cause

javax.ejb.EJBTransactionRolledbackException:枚举类的未知名称值br.com.aaa.xxx.entidade .TipoPessoa:F
....
......

javax.ejb.EJBTransactionRolledbackException: Unknown name value for enum class br.com.aaa.xxx.entidade.TipoPessoa: F .... ......

推荐答案

Hibernate没有知道并关心你的枚举中的id字段。所有它知道的是序数值(0和1)和名称(FISICA和JURIDICA)。如果要保留F和J,则必须将两个枚举常量重命名为F和J,并在实体中注释该字段:

Hibernate doesn't know and care about the id field inside your enum. All it knows about is the ordinal value (0 and 1) and the name (FISICA and JURIDICA). If you want to persist F and J, you'll have to rename your two enum constants to F and J, and annotate the field in the entity like this:

@Column(nullable=false, length=1)
@Enumerated(EnumType.STRING)
private TipoPessoa tipoPessoa;

或使用自定义用户类型将F转换为FISICA,反之亦然。

or use a custom user type to transform F to FISICA or vice-versa.

这篇关于Hibernate异常:枚举类的未知名称值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆