Com JDBC puro, como vcoês implementam uma query dinâmica?
Sempre fiz IFs dentro da classe, mas, há algum tempo atrás, conversando com o pessoal na faculdade, um cara me disse que isso é gambiarra (e realmente parece) e que isto deve ser resolvido com uma Stored Procedure na base.
Passei a adotar essa abordagem, mas hoje, com uma base Oracle que não é de nosso domínio, não consegui colocar a SP para funcionar. E, aquela história, prazo acabando, voltei a implementar na classe.
Eu já tinha a classe abaixo, e implementei um método toQueryString(). Assim:
import java.util.Date;
import br.com.celsomartins.date.DateService;
/**
* POJO to be argument on DAO Query methods
* @author Celso Martins
* @since 15/04/2009
*/
public class ArsQuery {
private Long arsNumber;
private String solutionAgent;
private Date initOpenedDate;
private Date endOpenedDate;
private Date initClosedDate;
private Date endClosedDate;
private Short status;
private Short complexity;
/**
* Transform the object's information in a plain String
*/
public String toString(){
String format = "dd/MM/yyyy HH:mm:ss";
return "[" + arsNumber + "]" + "[" + solutionAgent + "]" + "[" + status + "]" + "[" + complexity + "]" +
"[" + DateService.formatDate(initOpenedDate, format) + "]" +
"[" + DateService.formatDate(endOpenedDate, format) + "]" +
"[" + DateService.formatDate(initClosedDate, format) + "]" +
"[" + DateService.formatDate(endClosedDate, format) + "]";
}
/**
* Build a dynamic query
* @return a String containing the dynamic query build
*/
public String toQueryString() {
String sql = " SELECT * FROM tb_acc_ars_control ";
if (arsNumber != null) {
sql += " WHERE \"NUMBER\" = ? ";
}
if (solutionAgent != null) {
sql += findConnector(sql) + " solutionAgent = ? ";
}
if ((initOpenedDate != null) && (endOpenedDate != null)) {
sql += findConnector(sql) + " created BETWEEN ? AND ? ";
}
if ((initClosedDate != null) && (endClosedDate != null)) {
sql += findConnector(sql) + " closed BETWEEN ? AND ? ";
}
if (complexity != null) {
sql += findConnector(sql) + " score = ? ";
}
if (status != null) {
sql += findConnector(sql) + " status = ? ";
}
return sql;
}
private String findConnector(String sql) {
if (sql.toLowerCase().contains("where")) {
return " AND ";
}else {
return " WHERE ";
}
}
}
Um dos meus incômodos é com o método findConnector que, apesar de não gostar, acho melhor que colocar o famoso (e famigerado) WHERE 1 = 1 ou WHERE NULL is NULL no início da query.
Como vocês implementam este tipo de coisa, quando não está usando Hibernate, iBatis…
P.S. Não reparem no poor english
Obrigado
