正如我在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)
这样的代码比上面的样板代码更糟糕。
注::转换代码:
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());
}
}
感谢Xtreme Biker的评论,将ss.beginTransaction().commit()
改为ss.getTransaction().commit()
, TransactionException
不见了
把getCurrentSession()
改成openSession()
,去掉SessionException
。
最后将查询行改为List instituicoes = ss.createCriteria(Instituicao.class).add(Restrictions.like("inst_nome", searchKeyword, MatchMode.START).ignoreCase()).list();
,问题就解决了。