This library provides a convenient query-by-criteria style SQL generator in the QueryBuilder.

See:
          Description

Packages
org.skife.sql  

 

This library provides a convenient query-by-criteria style SQL generator in the QueryBuilder. It allows out-of-order addition of elements, will map prepared statement bindinf values for elements ( which is needed when doing outof order generation), etc.

Sample usage:


public List findEmployees(Map constraints) throws SQLException
{
    PreparedStatement stmt = null;
    Connection conn = null;
    try
    {
        QueryBuilder qb = QueryBuilder.select().all().from("employees e");
        Map bindings = new HashMap();
        if (constraints.containsKey("firstName"))
        {
            qb.where("e.first_name like {firstName}");
            bindings.put("firstName", "%" + constraints.get("firstName") + "%");
        }
        if (constraints.containsKey("lastName"))
        {
            qb.where("e.last_name like {lastName}");
            bindings.put("lastName", "%" + constraints.get("lastName") + "%");
        }
        if (constraints.containsKey("departmentName")
        {
            qb.leftOuterJoin("employees e", "departments d",
                             "e.dept_id = d.id and d.name like {deptName}");
            bindings.put("deptName" "%" + constraints.get("departmentName") + "%");
        }
        Connection conn = // Obtain a connection;
        PreparedStatement stmt = conn.prepareStatement(qb.getQueryString());
        qb.bind(stmt, bindings);
        ResultSet results = stmt.executeQuery();

        List emps = new ArrayList();
        while (results.next())
        {
            emps.add(buildEmployee(ResultSet));
        }
        return Collections.unmodifiableList(emps);
    }
    finally
    {
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
    }
}