正如我在 PrimeFaces 展示中所读到的,我的 autoComplete 需要一个转换器才能工作,所以我做了如下操作:
<p:autoComplete id="ListaInst"
emptyMessage="Nenhuma instituição encontrada."
value="#{InstituicaoController.inst1}"
completeMethod="#{InstituicaoController.getInstituicoesLike}"
var="i"
itemLabel="#{i.inst_nome}"
itemValue="#{i}"
converter="instituicaoConverter"
required="true"
style="width: 200px;font-family: monospace; font-size: 14px; margin-top: 4px;" />
托管bean方法:
public Collection<Instituicao> getInstituicoesLike(String searchKeyword) {
InstituicaoDao dao = new InstituicaoDao();
Collection<Instituicao> instituicoes = dao.getInstituicoesLike(searchKeyword);
return instituicoes;
}
DAO方法:
public Collection<Instituicao> getInstituicoesLike(String searchKeyword) {
Session ss = HibernateUtil.getSessionFactory().getCurrentSession();
try {
ss.beginTransaction();
List instituicoes = ss.createCriteria(Instituicao.class).add(Restrictions.like("inst_nome", searchKeyword)).list();
ss.beginTransaction().commit();
ss.close();
ss.clear();
return instituicoes;
} catch(HibernateException e) {
ss.getTransaction().rollback();
ss.close();
ss.clear();
}
return null;
}
我知道使用 JTA、JPA 2.1、JSF 2.2、EJB 3.1 和 Hibernate 4.3.4 会更好(并且使用它们可以完美地工作),但我不知道在我正在处理的项目中是否可以接受。心胸狭隘的开发人员不想“重新学习所有内容”并认为类似代码this.manager.persist(entity)
比上面的样板代码更糟糕。
PS:转换器代码:
package br.com.solidaria.converters;
import br.com.solidaria.dao.InstituicaoDao;
import br.com.solidaria.model.Instituicao;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.faces.convert.*;
/**
*
* @author Rodrigo Sieja Bertin
*/
@FacesConverter(forClass = Instituicao.class, value = "instituicaoConverter")
public class InstituicaoConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
InstituicaoDao dao = new InstituicaoDao();
Instituicao i = InstituicaoDao.getById(Integer.parseInt(value));
return i;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
Instituicao i = (Instituicao) value;
return String.valueOf(i.getId());
}
}