SelectItemsConverter Omnifaces从数据库中预先选择

时间:2015-10-05 23:34:21

标签: jsf omnifaces

我遇到了一个问题:当我将对象保存到数据库时,它工作正常,但是当我想从数据库中检索它时,它不起作用。我使用的是Omnifaces 1.8.3中的selectItemsConverter(我也试过1.10)

AutomacaoEmail.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

...

@ManyToOne(fetch = FetchType.EAGER)
private ModeloEmail modeloEmail;

...

@Override
public int hashCode() {
    int hash = 7;
    hash = 31 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final AutomacaoEmail other = (AutomacaoEmail) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return String.format("%s[id=%d]", getClass().getSimpleName(), getId());
}

loadFromDatabaseMethod()

    List<ModeloEmail> modelosTemp = modeloEmailFacade.buscarTodos();
    SelectItemsBuilder selectItemsBuilder = new SelectItemsBuilder();
    if (modelosTemp != null) {
        for (ModeloEmail modeloEmail : modelosTemp) {
            selectItemsBuilder.add(modeloEmail, modeloEmail.getNome());
        }
        modelosEmails = selectItemsBuilder.buildList();
    }

page.xhtml

<p:selectOneMenu value="#{automacaoEmailsController.automacaoEmail.modeloEmail}" converter="omnifaces.SelectItemsConverter">
    <f:selectItem noSelectionOption="true" itemLabel="Selecionar um modelo"/>
    <f:selectItems value="#{automacaoEmailsController.modelosEmails}"/>
</p:selectOneMenu>

我也试过了SelectItemsIndexConverter

1 个答案:

答案 0 :(得分:2)

if (getClass() != obj.getClass()) {
    return false;
}

equals()是JPA实现特定的代理类时,obj方法中的此测试可能会失败,例如Hibernate用于例如懒惰的实体。这至少可以解释为什么它似乎“有时”起作用。

如果您确实在使用Hibernate,那么您需要通过以下测试替换上述测试:

if (Hibernate.getClass(this) != Hibernate.getClass(obj)) {
    return false;
}

或者通过以下更通用(不依赖于Hibernate)的测试:

if (!(obj.getClass().isAssignableFrom(getClass()) && getClass().isAssignableFrom(obj.getClass()))) {
    return false;
}