I have a search page with multiple search criteria
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.
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 ...
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) ?
Prepared statements are interesting from a stored programming perspective because they allow us to create dynamic SQL calls. The SQL text may contain placeholders for data values that must be supplied when the SQL is executed.
To execute a statement with Where clause using PreparedStatement. Prepare the query by replacing the value in the clause with place holder “?” and, pass this query as a parameter to the prepareStatement() method.
Native dynamic SQL enables you to place dynamic SQL statements directly into PL/SQL code. These dynamic statements include DML statements (including queries), PL/SQL anonymous blocks, DDL statements, transaction control statements, and session control statements.
I wouldn't like using a StringBuilder
to dynamically create a query each and every time, especially when the number of meaningful combinations is countable and finite.
I'd always prefer static Strings. Yes, you have to type them in, but you'll do that once. I'd rather do that than pay the price in complexity and at runtime.
In such conditions I prefer adding 1=1
in where clause so that you dont have to keep track of where to insert AND
.
String selectClause = "SELECT * FROM EMPLOYEES WHERE 1=1 ";
if(StringUtils.isNotBlank(empName)){
selectQuery += "AND EMP_NAME = " + empName;
}
if(StringUtils.isNotBlank(empID)){
selectQuery += "AND EMP_ID = " + empID;
}
//... and so on ...
Related question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With