[英]Multiple filter in sql query (JDBC)
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. 我没有使用休眠而是使用JDBC模板。
I've Employee table with following attributes 我有以下属性的员工表
Requirement : 1.Write getByFilter API in EmployeeDAO. 要求:1.在EmployeeDAO中编写getByFilter API。 2.If any of the field is null in the filter object ignore that in the query.
2.如果过滤器对象中的任何字段为null,则在查询中忽略该字段。
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 休眠条件提供了更好的选项来编写数据库查询以及更简便,更干净的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.