If I understand correctly, you would like to generate queries dynamically, depending on the value of input fields. There are frameworks helping to do that, like MyBatis. But you could roll your own solution with prepared statements :
String query = "select * from foo f";
List<String> clauses = new ArrayList<String>();
List<Object> parameters = new ArrayList<Object>();
if (firstName != null) {
clauses.add("f.name = ?");
parameters.add(firstName);
}
// ...
if (!clauses.isEmpty()) {
query += " where " + StringUtils.join(clauses, " and ");
}
PreparedStatement ps = connection.prepareStatement(query);
for (int i = 0; i < parameters.size(); i++) {
ps.setObject(i + 1, paremeters.get(i));
}
You could make it even better by supporting SQL types, by using the builder pattern, etc., but you should get the idea with this simple example.