I came up with the solution and wanted to know any other better approach to handle this problem ?
I am not using hibernate instead using JDBC template.
I've Employee table with following attributes
Requirement : 1.Write getByFilter API in EmployeeDAO. 2.If any of the field is null in the filter object ignore that in the query.
Solution : I came up with following generic solution.
public List<Employee> getByFilter(Employee filter){
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
getDataSource());
String query = "SELECT ID as id,"+
"first_name as firstName,"+
"last_name as lastName,"+
"dob as dob ,"+
"department_name as departmentName,"+
"salary as salary"+
"FROM employee "+
"WHERE "+
"(:id IS NULL OR id = :id ) AND"+ // Handling second requirement if field is null
"(:first_name IS NULL or first_name = :firstName ) AND"+
"(:last_name IS NULL or first_name = :lastName) AND"+
"(:salary IS NULL OR salary = :salary)";
Map<String, Object> aMap = new HashMap<String, Object>();
aMap.put("id", filter.getId());
aMap.put("firstName", filter.getFirstName());
aMap.put("lastName", filter.getLastName());
aMap.put("salary", filter.getSalary());
return namedParameterJdbcTemplate.query(getQuery, aMap,
new BeanPropertyRowMapper<Employee>(Employee.class));
}
A better option can be to use hibernate criteria so that it will reduce the query
Criteria criteria = session.createCriteria(classname);
criteria.add(Restrictions.eq("first_name", firstName));
criteria.add(Restrictions.eq("last_name", lastName));
//same for all properties
//for checking null it will be like
criteria.add(Restrictions.isNotNull("id "));
//same for others
hibernate criteria provides better options to write the database query and easier and cleaner approach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.