I have a search page with multiple search criteria
- Employee Name
- Employee Id
- Date of joining
- Department
etc
User can provide one or more search criteria. I need to query database to get the search results.
Using plain JDBC, there are two options to achieve this.
- Prepare SQL query by appending search criteria provided by user.
ex:
String selectClause = "SELECT * FROM EMPLOYEES WHERE ";
String whereClause = "";
if(StringUtils.isNotBlank(empName)){
if(whereClause.length > 0){
whereClause += " AND ";
}
selectQuery += " EMP_NAME = " + empName;
}
if(StringUtils.isNotBlank(empID)){
if(whereClause.length > 0){
whereClause += " AND ";
}
selectQuery += " EMP_ID = " + empID;
}
//... and so on ...
- Using
preparestatement
ex:
String query = "SELECT * FROM EMPLOYEES WHERE EMP_NAME = ? AND EMP_ID = ? DATE_OF_JOINING = ? AND DEPARTMENT = ?";
This answer explains that like ex 1 above, ex2 can be modified, something like below
String selectClause = "SELECT * FROM EMPLOYEES WHERE ";
String whereClause = "";
if(StringUtils.isNotBlank(empName)){
if(whereClause.length > 0){
whereClause += " AND ";
}
selectQuery += " EMP_NAME = ?";
}
if(StringUtils.isNotBlank(empID)){
if(whereClause.length > 0){
whereClause += " AND ";
}
selectQuery += " EMP_ID = ?";
}
//... and so on ...
Then carefully (keeping parameter index in mind) the input needs to set to the prepared statement. This doesn't sounds to be a very ideal solution.
Is there a way to do this in an elegant way (without ORM frameworks) ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…