Primefaces selectOneMenu 转换器调用但不工作

Primefaces selectOneMenu converter called but not working

我查看了其他问题 this and this,等等,问题是我的转换被调用但 selectOneMenu 的值没有改变。我的实体 class 已生成,并且具有等于和 hashCode,我不想更改其中的任何内容 - 如果它被重新生成,那么所有更改都将丢失(解决方法是更改​​实体的 toString class).

截取的 XHTML 代码:

<p:selectOneMenu id="defid" 
                 value="#{abcController.selected.defid}"
                 converter="defConverter">

转换器:

@FacesConverter("defConverter")
public class DefConverter implements Converter
{
    private static final Logger LOG = Logger.getLogger(DefConverter.class.getName());
    @EJB
    private DefFacade defFacade;

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string)
    {
        LOG.info("getAsObject: " + string);
        try
        {
            return defFacade.findWithNFieldsWithValue("name", string, "=").get(0);
        }
        catch (Exception ex)
        {
            LOG.log(Level.SEVERE, "Error while fetching Def for " + string, ex);
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object obj)
    {
        LOG.info("getAsString obj class: " + obj.getClass().getName());
        if(obj instanceof Def)
        {
            Def def = (Def)obj;
            LOG.info("getAsString def name: " + def.getName());
            return def.getName();
        }
        else
        {
            StringBuilder sbError = new StringBuilder("The object of class ");
            sbError.append(obj.getClass().getName()).append(" is not of Def");
            throw new ClassCastException(sbError.toString());
        }
    }
}

被截断的实体class(这是生成的):

...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "defid")
private Long defid;
...

@Override
public int hashCode()
{
    int hash = 0;
    hash += (defid != null ? defid.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object)
{
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Def))
    {
        return false;
    }
    Def other = (Def) object;
    if ((this.defid == null && other.defid != null) || (this.defid != null && !this.defid.equals(other.defid)))
    {
        return false;
    }
    return true;
}

当页面加载时,我可以看到如下日志语句:

getAsString obj class: com.xyz.Def
getAsString def name: Name 1
getAsString obj class: com.xyz.Def
getAsString def name: Name 2
getAsString obj class: com.xyz.Def
getAsString def name: Name 3

因此转换器被调用并且 returns 正确的值但在页面上它仍然是 com.xyz.Def[ defid=1 ] (下拉和正常)

转换器似乎可以正常工作,但您没有 post 整个 <p:selectOneMenu> 代码,尤其是 <f:selectItems>。它应该看起来像这样

<p:selectOneMenu id="defid" 
                 value="#{abcController.selected.defid}"
                 converter="defConverter">
    <f:selectItems value="#{abcController.defs}" var="def"
                       itemLabel="#{def.name}" itemValue="#{def.defId}" />
</p:selectOneMenu>

itemLabel负责打印显示值。