Ejemplo de paginación (Listado de preguntas pendientes) con primefaces

utilizando LazyDataModel, con recarga automática de la página
solicitada.
This commit is contained in:
Marcos Garcia Nuñez
2019-12-16 22:02:27 +01:00
parent dcbebe5253
commit 9bfdebbea4
12 changed files with 250 additions and 54 deletions

View File

@@ -28,13 +28,13 @@
</h:outputScript> </h:outputScript>
<h:body> <h:body>
<div id="layout"> <div id="layout">
<p:growl id="messages" globalOnly="true" sticky="false" showDetail="true" life="15000" />
<div id="top" class="top"> <div id="top" class="top">
<!-- <h1 class="Titulo">myHealth Site</h1> --> <!-- <h1 class="Titulo">myHealth Site</h1> -->
<h:graphicImage library="images" name="logo-small.png" /> <h:graphicImage library="images" name="logo-small.png" />
</div> </div>
<hr /> <hr />
<div id="menuDiv"> <div id="menuDiv">
<p:growl id="messages" globalOnly="true" sticky="false" showDetail="true" life="15000" />
<p:ajaxStatus style="width:32px; height:32px; position:fixed; right:32px; bottom:32px"> <p:ajaxStatus style="width:32px; height:32px; position:fixed; right:32px; bottom:32px">
<f:facet name="start"> <f:facet name="start">
<i id="loginSpin" class="pi pi-spin pi-spinner" style="font-size: 3em"></i> <i id="loginSpin" class="pi pi-spin pi-spinner" style="font-size: 3em"></i>

View File

@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="../header.xhtml">
<ui:define name="content">
<h:form id="TestForm">
<p:messages id="mesgs" showDetail="true" closable="true" autoupdate="true" />
<p:panel id="panelPendingQuestions" header="Listado de preguntas pendientes de respuesta">
<div class="ui-g ui-fluid">
<div class="ui-g-4 ui-md-4">
<p:outputLabel for="campo" value="Etiqueta para campo de formulario:" />
</div>
<div class="ui-g-4 ui-md-4">
<p:inputText id="campo" value="Valor del campo del formulario" required="true" requiredMessage="Por favor, especifique un valor" />
</div>
<div class="ui-g-4 ui-md-4">
<p:message for="campo" display="text" />
</div>
<div class="ui-g-4 ui-md-4">
<p:outputLabel for="campo2" value="Etiqueta para campo 2 de formulario:" />
</div>
<div class="ui-g-4 ui-md-4">
<p:inputText id="campo2" value="Valor del campo 2 del formulario" required="true" requiredMessage="Por favor, especifique un valor" />
</div>
<div class="ui-g-4 ui-md-4">
<p:message for="campo" display="text" />
</div>
<div class="ui-g-4 ui-md-4">
<p:outputLabel for="campo3" value="Etiqueta para campo 3 de formulario:" />
</div>
<div class="ui-g-4 ui-md-4">
<p:inputText id="campo3" value="Valor del campo 3 del formulario" required="true" requiredMessage="Por favor, especifique un valor" />
</div>
<div class="ui-g-4 ui-md-4">
<p:message for="campo" display="text" />
</div>
<p:dataTable var="qs" value="#{PendingQuestions.lazyDataModelQuestionList}" lazy="true" paginator="true" rows="10" paginatorPosition="bottom" paginatorAlwaysVisible="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="10,20,30,40">
<p:column headerText="Id" width="60px;">
<h:outputText value="#{qs.id}" />
</p:column>
<p:column headerText="Title" width="auto">
<h:outputText value="#{qs.title}"/>
</p:column>
<p:column headerText="Patient" width="auto">
<h:outputText value="#{qs.patient.displayName}" />
</p:column>
<p:column headerText="Status" width="90px;">
<h:outputText value="#{qs.status}" />
</p:column>
<p:column headerText="Acción" width="80px;">
<h:outputText value="Responder" />
</p:column>
<f:facet name="paginatorTopLeft">
<p:commandButton type="button" icon="pi pi-refresh" />
</f:facet>
</p:dataTable>
<div class="ui-g-12 ui-g-nopad">
<div class="ui-g-4 ui-md-4" />
<div class="ui-g-2 ui-md-2 ">
<p:commandButton validateClient="true" value="Guardar" update="TestForm" action="#{BeanName.actionMethod}" icon="pi pi-check" />
</div>
<div class="ui-g-2 ui-md-2">
<p:button value="Volver" outcome="/home" icon="pi pi-home" />
</div>
<div class="ui-g-4 ui-md-4" />
</div>
</div>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</html>

View File

@@ -9,4 +9,6 @@ public class Constants {
public static final int MAX_ITEMS_AUTOCOMPLETE_SEARCH = 200; public static final int MAX_ITEMS_AUTOCOMPLETE_SEARCH = 200;
public static final String PROFESSIONAL_NUMBER_PREFIX = "PRO#"; public static final String PROFESSIONAL_NUMBER_PREFIX = "PRO#";
public static final String PERSONAL_IDENTIFICATION_CODE_PREFIX = "PAT#"; public static final String PERSONAL_IDENTIFICATION_CODE_PREFIX = "PAT#";
public static final int DEFAULT_TABLE_GRID_PAGE_SIZE = 20;
} }

View File

@@ -6,21 +6,20 @@ import java.util.List;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import org.jboss.security.auth.spi.Users.User;
import TO.FamilyDoctorTO; import TO.FamilyDoctorTO;
import TO.MedicalSpecialtyTO; import TO.MedicalSpecialtyTO;
import TO.PatientTO; import TO.PatientTO;
import TO.PrimaryHealthCareCenterTO; import TO.PrimaryHealthCareCenterTO;
import TO.QuestionTO;
import TO.SpecialistDoctorTO; import TO.SpecialistDoctorTO;
import common.Utils; import common.Utils;
import jpa.FamilyDoctorJPA; import jpa.FamilyDoctorJPA;
import jpa.MedicalSpecialtyJPA; import jpa.MedicalSpecialtyJPA;
import jpa.PatientJPA; import jpa.PatientJPA;
import jpa.PrimaryHealthCareCenterJPA; import jpa.PrimaryHealthCareCenterJPA;
import jpa.QuestionJPA;
import jpa.SpecialistDoctorJPA; import jpa.SpecialistDoctorJPA;
@Stateless @Stateless
@@ -311,4 +310,24 @@ public class CommonFacadeBean implements CommonFacadeRemote, CommonFacadeLocal {
else else
return null; return null;
} }
public QuestionTO getPOJOforQuestionJPA(QuestionJPA qs, int nestedProps) {
QuestionTO qsTO = null;
if (qs != null) {
FamilyDoctorJPA fd = null;
PatientJPA pat = null;
if (nestedProps > 0) {
fd = qs.getFamilyDoctor();
pat = qs.getPatient();
}
nestedProps--;
qsTO = new QuestionTO(qs.getId(), qs.getTitle(), qs.getMessage(), qs.getStatus(), this.getPOJOforPatientJPA(pat, nestedProps),
this.getPOJOforFamilyDoctorJPA(fd, nestedProps), qs.getResponse());
}
return qsTO;
}
} }

View File

@@ -1,6 +1,5 @@
package ejb.common; package ejb.common;
import java.util.Collection;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
@@ -9,11 +8,13 @@ import TO.FamilyDoctorTO;
import TO.MedicalSpecialtyTO; import TO.MedicalSpecialtyTO;
import TO.PatientTO; import TO.PatientTO;
import TO.PrimaryHealthCareCenterTO; import TO.PrimaryHealthCareCenterTO;
import TO.QuestionTO;
import TO.SpecialistDoctorTO; import TO.SpecialistDoctorTO;
import jpa.FamilyDoctorJPA; import jpa.FamilyDoctorJPA;
import jpa.MedicalSpecialtyJPA; import jpa.MedicalSpecialtyJPA;
import jpa.PatientJPA; import jpa.PatientJPA;
import jpa.PrimaryHealthCareCenterJPA; import jpa.PrimaryHealthCareCenterJPA;
import jpa.QuestionJPA;
import jpa.SpecialistDoctorJPA; import jpa.SpecialistDoctorJPA;
/** /**
@@ -70,4 +71,5 @@ public interface CommonFacadeLocal {
public PatientTO getPOJOforPatientJPA(PatientJPA pat, int nestedProps); public PatientTO getPOJOforPatientJPA(PatientJPA pat, int nestedProps);
public QuestionTO getPOJOforQuestionJPA(QuestionJPA qs, int nestedProps);
} }

View File

@@ -1,20 +1,21 @@
package ejb.medicalTest; package ejb.medicalTest;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.Stateless; import javax.ejb.Stateless;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import TO.FamilyDoctorTO;
import TO.LoggedUserTO; import TO.LoggedUserTO;
import TO.MedicalSpecialtyTO; import TO.MedicalSpecialtyTO;
import TO.MedicalTestTO.MedicalTestType; import TO.MedicalTestTO.MedicalTestType;
import TO.PatientTO; import TO.QuestionTO;
import common.QuestionStatus; import common.QuestionStatus;
import common.UserType; import common.UserType;
import TO.QuestionTO;
import ejb.common.CommonFacadeLocal; import ejb.common.CommonFacadeLocal;
import jpa.FamilyDoctorJPA; import jpa.FamilyDoctorJPA;
import jpa.PatientJPA; import jpa.PatientJPA;
@@ -34,10 +35,9 @@ import managedbean.common.SessionUtils;
*/ */
@Stateless @Stateless
public class MedicalTestFacadeBean implements MedicalTestFacadeRemote { public class MedicalTestFacadeBean implements MedicalTestFacadeRemote {
// Persistence Unit Context // Persistence Unit Context
@PersistenceContext(unitName = "MyHealth") @PersistenceContext(unitName = "MyHealth")
private EntityManager entman; EntityManager entman;
@EJB @EJB
CommonFacadeLocal commonServices; CommonFacadeLocal commonServices;
@@ -77,13 +77,36 @@ public class MedicalTestFacadeBean implements MedicalTestFacadeRemote {
public void answerQuestion(String question, String response) { public void answerQuestion(String question, String response) {
} }
/** public List<QuestionTO> listAllPendingQuestions(int familyDoctorId) {
* Recuperar las preguntas sin respuesta para un médico return null;
* }
* @param professionalNumber
*/ public Long getPendingQuestionsCount(int familyDoctorId) {
@Override TypedQuery<Long> query = entman.createQuery("SELECT count(1) from QuestionJPA q where q.status=:status and q.familyDoctor.id=:docId", Long.class);
public void listAllPendingQuestions(int professionalNumber) { query.setParameter("status", QuestionStatus.PENDING);
query.setParameter("docId", familyDoctorId);
return query.getSingleResult();
}
public List<QuestionTO> listPendingQuestionsPaged(int familyDoctorId, int pageNumber, int pageSize) {
TypedQuery<QuestionJPA> query = entman.createQuery("SELECT q from QuestionJPA q where q.status=:status and q.familyDoctor.id=:docId order by q.title", QuestionJPA.class);
query.setParameter("status", QuestionStatus.PENDING);
query.setParameter("docId", familyDoctorId);
if (pageSize > 0) {
query.setFirstResult(pageNumber * pageSize);
query.setMaxResults(pageSize);
}
List<QuestionJPA> allJPA = query.getResultList();
List<QuestionTO> pendingQuestions = new ArrayList<QuestionTO>();
for (QuestionJPA item : allJPA) {
pendingQuestions.add(commonServices.getPOJOforQuestionJPA(item, 1));
}
return pendingQuestions;
} }
/** /**

View File

@@ -1,11 +1,13 @@
package ejb.medicalTest; package ejb.medicalTest;
import java.util.Date; import java.util.Date;
import java.util.List;
import javax.ejb.Remote; import javax.ejb.Remote;
import TO.MedicalSpecialtyTO; import TO.MedicalSpecialtyTO;
import TO.MedicalTestTO.MedicalTestType; import TO.MedicalTestTO.MedicalTestType;
import TO.QuestionTO;
/** /**
* Interfaz remota del EJB Definimos los métodos que estarán disponibles para * Interfaz remota del EJB Definimos los métodos que estarán disponibles para
@@ -42,9 +44,13 @@ public interface MedicalTestFacadeRemote {
* *
* De utilidad para paciente y médico de familia. No para médico especialista. * De utilidad para paciente y médico de familia. No para médico especialista.
* *
* @param professionalNumber * @param familydoctorid
*/ */
public void listAllPendingQuestions(int professionalNumber); public List<QuestionTO> listAllPendingQuestions(int familyDoctorId);
public Long getPendingQuestionsCount(int familyDoctorId);
public List<QuestionTO> listPendingQuestionsPaged(int familyDoctorId, int pageNumber, int pageSize);
/** /**
* Recuperar una pregunta por su String * Recuperar una pregunta por su String

View File

@@ -1,7 +1,7 @@
package jpa; package jpa;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.List;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
@@ -28,7 +28,7 @@ public class FamilyDoctorJPA implements Serializable {
@Id @Id
@Column(updatable = false) @Column(updatable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
private String professionalNumber; private String professionalNumber;
@@ -39,9 +39,9 @@ public class FamilyDoctorJPA implements Serializable {
private String email; private String email;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "FamilyDoctorId") @JoinColumn(name = "FamilyDoctorId")
private Collection<PatientJPA> patients; private List<PatientJPA> patients;
@ManyToOne @ManyToOne
@JoinColumn (name="PrimaryHealthCareCenterId") @JoinColumn(name = "PrimaryHealthCareCenterId")
private PrimaryHealthCareCenterJPA primaryHealthCareCenter; private PrimaryHealthCareCenterJPA primaryHealthCareCenter;
/** /**
@@ -111,19 +111,21 @@ public class FamilyDoctorJPA implements Serializable {
/** /**
* Metodos para get/set de relaciones (pacientes) * Metodos para get/set de relaciones (pacientes)
*
* @return * @return
*/ */
public Collection<PatientJPA> getPatients() { public List<PatientJPA> getPatients() {
return patients; return patients;
} }
public void setPatients(Collection<PatientJPA> patients) { public void setPatients(List<PatientJPA> patients) {
this.patients = patients; this.patients = patients;
} }
public PrimaryHealthCareCenterJPA getPrimaryHealthCareCenter() { public PrimaryHealthCareCenterJPA getPrimaryHealthCareCenter() {
return primaryHealthCareCenter; return primaryHealthCareCenter;
} }
public void setPrimaryHealthCareCenter(PrimaryHealthCareCenterJPA center) { public void setPrimaryHealthCareCenter(PrimaryHealthCareCenterJPA center) {
this.primaryHealthCareCenter = center; this.primaryHealthCareCenter = center;
} }

View File

@@ -5,6 +5,8 @@ import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
@@ -12,11 +14,12 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
import common.TestType;
/** /**
* Los nombres de los decortadores relacionados con la BBDD pueden estar * Los nombres de los decortadores relacionados con la BBDD pueden estar en
* en camelCase, snakeCase o como se quiera, puesto que en persistence.xml * camelCase, snakeCase o como se quiera, puesto que en persistence.xml se tiene
* se tiene dicho que se convierta a minúsculas. * dicho que se convierta a minúsculas.
* *
* Lo uso en minúsculas para mejorar la trazabilidad de los campos. * Lo uso en minúsculas para mejorar la trazabilidad de los campos.
* *
@@ -30,29 +33,30 @@ public class MedicalTestJPA implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; private int id;
private Date date; private Date date;
private long time; private long time;
private String observations; private String observations;
private String highresimage; private String highresimage;
@Column(name = "type") // Con esto podríamos cambiar los nombres de las propiedades de la clase y mantener la relación con la BBDD a través de JPA @Enumerated(EnumType.STRING)
private int type; @Column(name = "type") // Con esto podríamos cambiar los nombres de las propiedades de la clase y
// mantener la relación con la BBDD a través de JPA
private TestType type;
@ManyToOne @ManyToOne
@JoinColumn (name="patientid") @JoinColumn(name = "patientid")
private PatientJPA patient; private PatientJPA patient;
@ManyToOne @ManyToOne
@JoinColumn (name="specialistdoctorid") @JoinColumn(name = "specialistdoctorid")
private SpecialistDoctorJPA specialistDoctor; private SpecialistDoctorJPA specialistDoctor;
public MedicalTestJPA() { public MedicalTestJPA() {
super(); super();
} }
public MedicalTestJPA(int id, Date date, long time, String observations, String highresimage, int type, public MedicalTestJPA(int id, Date date, long time, String observations, String highresimage, TestType type, PatientJPA patient, SpecialistDoctorJPA specialistDoctor) {
PatientJPA patient, SpecialistDoctorJPA specialistDoctor) {
this.id = id; this.id = id;
this.date = date; this.date = date;
this.time = time; this.time = time;
@@ -103,11 +107,11 @@ public class MedicalTestJPA implements Serializable {
this.highresimage = highresimage; this.highresimage = highresimage;
} }
public int getType() { public TestType getType() {
return type; return type;
} }
public void setType(int type) { public void setType(TestType type) {
this.type = type; this.type = type;
} }
@@ -127,6 +131,4 @@ public class MedicalTestJPA implements Serializable {
this.specialistDoctor = specialistDoctor; this.specialistDoctor = specialistDoctor;
} }
} }

View File

@@ -3,6 +3,8 @@ package jpa;
import java.io.Serializable; import java.io.Serializable;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
@@ -29,6 +31,7 @@ public class QuestionJPA implements Serializable {
private int id; private int id;
private String title; private String title;
private String message; private String message;
@Enumerated(EnumType.STRING)
private QuestionStatus status; private QuestionStatus status;
private String response; private String response;
@@ -38,19 +41,18 @@ public class QuestionJPA implements Serializable {
@ManyToOne @ManyToOne
@JoinColumn(name = "familydoctorid") @JoinColumn(name = "familydoctorid")
private FamilyDoctorJPA familydoctor; private FamilyDoctorJPA familyDoctor;
public QuestionJPA() { public QuestionJPA() {
} }
public QuestionJPA(int id, String title, String message, QuestionStatus status, PatientJPA patient, public QuestionJPA(int id, String title, String message, QuestionStatus status, PatientJPA patient, FamilyDoctorJPA familydoctor, String response) {
FamilyDoctorJPA familydoctor, String response) {
this.id = id; this.id = id;
this.title = title; this.title = title;
this.message = message; this.message = message;
this.status = status; this.status = status;
this.patient = patient; this.patient = patient;
this.familydoctor = familydoctor; this.familyDoctor = familydoctor;
this.response = response; this.response = response;
} }
@@ -94,12 +96,12 @@ public class QuestionJPA implements Serializable {
this.status = status; this.status = status;
} }
public FamilyDoctorJPA getDoctor() { public FamilyDoctorJPA getFamilyDoctor() {
return familydoctor; return familyDoctor;
} }
public void setDoctor(FamilyDoctorJPA familydoctor) { public void setFamilyDoctor(FamilyDoctorJPA familyDoc) {
this.familydoctor = familydoctor; this.familyDoctor = familyDoc;
} }
public String getResponse() { public String getResponse() {

View File

@@ -104,7 +104,7 @@ public class MenuMBean implements Serializable {
subMenu.addElement(createMenuItem("Responder pregunta", "fa fa-comments", "/medicaltest/MedicalTests", null)); subMenu.addElement(createMenuItem("Responder pregunta", "fa fa-comments", "/medicaltest/MedicalTests", null));
if (tipoUsuario == UserType.FAMILY_DOCTOR) if (tipoUsuario == UserType.FAMILY_DOCTOR)
subMenu.addElement(createMenuItem("Ver preguntas pendientes", "fa fa-comments-o", "/medicaltest/MedicalTests", null)); subMenu.addElement(createMenuItem("Ver preguntas pendientes", "fa fa-comments-o", "/medicaltest/PendingQuestions", null));
model.addElement(subMenu); model.addElement(subMenu);
} }

View File

@@ -0,0 +1,53 @@
package managedbean.medicalTest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import TO.QuestionTO;
import common.Constants;
import ejb.medicalTest.MedicalTestFacadeRemote;
import managedbean.common.ManagedBeanBase;
import managedbean.common.SessionUtils;
@Named("PendingQuestions")
@ViewScoped
public class PendingQuestionsMBean extends ManagedBeanBase implements Serializable {
private static final long serialVersionUID = 1L;
private int familyDoctorId;
private LazyDataModel<QuestionTO> lazyDataModelQuestionList;
public PendingQuestionsMBean() {
}
@PostConstruct
public void init() {
// Inicialización de variables y propiedades van aquí.
this.familyDoctorId = Integer.valueOf(SessionUtils.getUserId());
this.lazyDataModelQuestionList = new LazyDataModel<QuestionTO>() {
private static final long serialVersionUID = 1L;
@Override
public List<QuestionTO> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
Long totalRowCount = getRemoteManagerMedicalTest().getPendingQuestionsCount(familyDoctorId);
this.setRowCount(totalRowCount.intValue());
return getRemoteManagerMedicalTest().listPendingQuestionsPaged(familyDoctorId, (first / pageSize), pageSize);
}
};
}
public LazyDataModel<QuestionTO> getLazyDataModelQuestionList() {
return lazyDataModelQuestionList;
}
}