I am using Liferay to develop a module. A part of involves fetching only those records form the database where the leave status of employees is Pending. the code that I have to fetch "Pending" records is:
@SuppressWarnings("unchecked")
public static List<Employee> getEmployeeData() throws PortalException, SystemException{
List<Employee> employeeDetails;
try{
int totalEmployees = EmployeeLocalServiceUtil.getEmployeesCount();
for(Employee emp: employeeDetails {
if(emp.getEmpStatus.equals("Pending") {
employeeDetails= EmployeeLocalServiceUtil.getEmployees(0,totalEmployees);
}
}
}catch(SystemException se){
employeeDetails = Collections.emptyList();
}
return employeeDetails;
}
The above code fetches all the details - Pending as well as non pending. This I know happens because of the statement in the above code:
employeeDetails= EmployeeLocalServiceUtil.getEmployees(0,totalEmployees);
since It fetches all the rows. So how should I structure and modify my code to get only the pending details?
A quick but really bad practice is keeping your code with this change :
List<Employee> employeeDetails = new ArrayList<Employee>;
try{
List<Employees> allEmployees = EmployeeLocalServiceUtil.getAllEmployees();
for(Employee emp: allEmployees {
if(emp.getEmpStatus.equals("Pending") {
employeeDetails.add(emp);
}
}return employeeDetails;
Now, the correct way to do this is :
go to EmployeeLocalServiceImpl, and add
public List getAllEmployeesByEmpStatus (String status) {
try {
return employeePersistence.findByEmpStatus(status);
} catch (SystemException e) {
e.printStackTrace(); return Collections.emptyList();
}
}
then build service again
Replace your code with
List employeeDetails = EmployeeLocalServiceUtil.getAllEmployeesByEmpStatus("Pending") ;
return employeeDetails;