to build a dynamic query through java code
I have one entity class which has certain tables attributes in it . The object of this class will be populated in a helper class with values fo开发者_开发问答r the attributes . Now i want a method that would dynamically build an SQL query statement( a separate private method), query the table ( a separate private method) for all matching rows, map the output results (a separate private method) to a list of AuditBO objects
Hope this will be helpful.
When the Table
class is initialized, all the input values will be initialized. When getSelectQuery
method is called, based on inputs select query will be formed. And populatePreparedSt
will be called to set PreparedStatement. Finally based on the inputs, you set in constructor of Table
, you will get the query and result.
Table class:
public class TableRow {
private String attibute1;
private String attibute2;
private int id;
// getter and setters
public final String selectQuery = " SELECT ID, ATTIBUTE1, ATTIBUTE2 FROM TABLEROW ";
public CECardLogRow(int id, String attibute1, String attibute2) {
this.id = id;
this.attibute1 = attibute1;
this.attibute2 = attibute2;
}
public String getSelectQuery () {
StringBuilder sql = new StringBuilder();
boolean whereClauseAdded = false;
sql = sql.append(selectQuery);
if (id > -1) {
sql.append(" WHERE ID = ? ");
whereClauseCt++;
}
if (attibute1 != null && attibute1.trim() != "") {
sql.append(whereClauseAdded ? " AND " : " WHERE ");
sql.append(" ATTIBUTE1 = ? ");
}
if (attibute2 != null && attibute2.trim() != "") {
sql.append(whereClauseAdded ? " AND " : " WHERE ");
sql.append(" ATTIBUTE2 = ? ");
}
return sql.toString();
}
public void populatePreparedSt (PreparedStatement ps) {
int i = 1;
if (id > -1) {
ps.setInt(i++, id);
}
if (attibute1 != null && attibute1.trim() != "") {
ps.setString(i++, attibute1);
}
if (attibute2 != null && attibute2.trim() != "") {
ps.setString(i++, attibute2);
}
}
}
Calling method:
public List<TableRow> getData (int id, String attibute1, String attibute2) {
List<TableRow> rows = new ArrayList<TableRow>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
TableRow row = new TableRow(id, attibute1, attibute2);
String sql = row.getSelectQuery();
con = global.getConnection(); // get connection
ps = con.prepareStatement(sql);
row.populatePreparedSt(ps);
rs = ps.executeQuery();
while (rs.next()) {
TableRow row = new TableRow();
// get data
row.setId(rs.getInt("ID"));// and so on
rows.add(tableRow);
}
} catch (SQLException sqe) {
throw sqe;
} finally() {
// closeConnection
}
return rows;
}
精彩评论