通过java代码构建动态查询

时间:2011-10-07 08:31:32

标签: java

我有一个实体类,其中包含某些表属性。此类的对象将填充在具有属性值的辅助类中。现在我想要一个动态构建SQL查询语句(一个单独的私有方法)的方法,查询所有匹配行的表(一个单独的私有方法),将输出结果(一个单独的私有方法)映射到一个AuditBO对象列表

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

初始化Table类时,将初始化所有输入值。调用getSelectQuery方法时,将根据输入选择查询形成。并且将调用populatePreparedSt来设置PreparedStatement。最后根据输入,您在Table的构造函数中设置,您将获得查询和结果。

表类:

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);
        }           
    }
}

通话方式:

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;
}