I have a search page with multiple search criteria
- Employee Name
- Employee id
- Date of joining
- The Department
etc.
A user may provide one or more search criteria. I need to query the database to get the search results.
Using simple JDBC, there are two options for this.
- Prepare the SQL query by adding the search criteria provided by the user.
Example:
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;
}
- 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 = ?";
}
Then, carefully (taking into account the parameter index), the input should be set to the prepared statement. This does not seem to be the ideal solution.
Is there a way to do this in an elegant way (without ORM structures)?