selectonemenu验证错误:值无效

use*_*884 3 java jsf hibernate

我正在使用这样的selectonemenu:

<h:selectOneMenu value="#{MyBean.zajecie.przedmiot}">
    <f:selectItems value="#{MyBean.przedmioty}" var="p"
        itemLabel="#{p.nazwa}" itemValue="#{p}" />
    <f:converter converterId="converter.PrzedmiotConverter" />
</h:selectOneMenu>
Run Code Online (Sandbox Code Playgroud)

为myBean:

private Zajecie zajecie;//+set get
private List<Przedmiot> przedmioty;//+set get

@PostConstruct
private void init() {
    przedmioty = przedmiotDao.findByLogin("login");
    zajecie = new Zajecie();
}
Run Code Online (Sandbox Code Playgroud)

和转换器方法:

public Object getAsObject(FacesContext context, UIComponent component, String value) {
    PrzedmiotDao przedmiotDao = DaoFactory.getInstance().getPrzedmiotDao();
    Przedmiot przedmiot = przedmiotDao.findById(Przedmiot.class, Integer.parseInt(value));
    return przedmiot;
}

public String getAsString(FacesContext context, UIComponent component, Object value) {
    Przedmiot przedmiot = (Przedmiot) value;
    String idAsString = String.valueOf(przedmiot.getPrzedmiotId());
    return idAsString;
}
Run Code Online (Sandbox Code Playgroud)

selectonemenu组件正在按预期填充.当我提交时,它显示Validation Error: Value is not valid.我知道我需要一个适合equals()我的实体的方法所以我只使用id字段用eclipse生成它.然后我不得不改变测试getClass() != obj.getClass(),obj instanceof Przedmiot因为obj.getClass()返回了这样的东西:Przedmiot_$$_javassist_1.我不确定这是否相关,因为毕竟obj证明了这一点null.我究竟做错了什么?

编辑:

MyBean是ViewScoped.

有趣的是,使用相同转换器的类似代码适用于应用程序的其他部分.不同的是,在工作部分我只是查看类型列表,Przedmiot我以另一种方式获取它.

@PostConstruct
private void init() {
    student = studentDao.findByLogin(ra.getUser());
}

<h:selectOneMenu value="#{otherBean.przedmiot}">
    <f:selectItems value="#{otherBean.student.grupa.przedmiots}" var="p" 
        itemLabel="#{p.nazwa}" itemValue="#{p}" />
    <f:converter converterId="converter.PrzedmiotConverter" />
</h:selectOneMenu>
Run Code Online (Sandbox Code Playgroud)

use*_*884 5

解决了它.这当然是写得不好的equals()方法.首先,我的问题出了问题.obj没有解决为null,但other.przedmiotId确实如此.对不起.看看eclipse生成的方法:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!(obj instanceof Przedmiot))//changed this from (getClass() != obj.getClass())
        return false;
    Przedmiot other = (Przedmiot) obj;
    if (przedmiotId == null) {
        if (other.przedmiotId != null)
            return false;
    } else if (!przedmiotId.equals(other.przedmiotId))
        return false;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

问题在于other.przedmiotId.使用getter获取值时,other.getPrzedmiotId()它不会再解析为null.