Autocompletado con Primefaces + JPA
Tabla: Nivel1
Tabla: Nivel1
Con NetBeans IDE generamos los Entity
Categories: Persistence File Types: Entity Classes from Database
Luego generar los EJB
Editamos Nivel1Facade.java y agregar los mƩtodos findByIdNivel1Like(), findByNombreLike().
public List<Nivel1> findByIdNivel1Like(String idnivel1) {
Query query = em.createQuery("SELECT n FROM Nivel1 n WHERE lower(n.idnivel1) like :idnivel1");
idnivel1 = "%" + idnivel1.trim() + "%";
return query.setParameter("idnivel1", idnivel1).getResultList();
}
public List<Nivel1> findByNombreLike(String nombre) {
Query query = em.createQuery("SELECT n FROM Nivel1 n WHERE lower(c.nombre) like :nombre");
nombre = "%" + nombre.trim() + "%";
return query.setParameter("nombre", nombre).getResultList();
}
Editar Nivel1SearchController.java
Agregar los mƩtodos complete(), completeNombre()
public List<Nivel1> complete(String query) {
List<Nivel1> suggestions = new ArrayList<>();
try {
query = query.trim();
nivel1Facade.findByIdNivel1Like(query.toLowerCase());
nivel1List.stream().forEach((p) -> {
suggestions.add(p);
});
} catch (Exception e) {
JSFUtil.addErrorMessage("complete() "+e.getLocalizedMessage());
}
return suggestions;
}
public List<Nivel1> completeNombre(String query) {
List<Nivel1> suggestions = new ArrayList<>();
try {
query = query.trim();
nivel1Facade.findByNombreLike(query.toLowerCase());
nivel1List.stream().forEach((p) -> {
suggestions.add(p);
});
} catch (Exception e) {
JSFUtil.addErrorMessage("completeNombre() "+e.getLocalizedMessage());
}
return suggestions;
}
En la pƔgina .xhtml
<p:outputLabel rendered="#{!nivel1Controller.nuevoregistro}" value="#{msg.idnivel1}" for="idnivel1" />
<p:autoComplete size="45" rendered="#{!nivel1Controller.nuevoregistro}" value="#{nivel1Controller.selected}"
completeMethod="#{nivel1SearchController.complete}"
var="p"
itemLabel="#{p.idnivel1}" itemValue="#{p}" converter="nivel1Converter" forceSelection="true">
<p:ajax event="itemSelect" listener="#{nivel1Controller.handleSelect}" update=":form,:form:growl" />
<f:facet name="itemtip">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="#{p.nombre}" />
</h:panelGrid>
</f:facet>
</p:autoComplete>
Comments