日期:2014-05-16 浏览次数:20494 次
/** * 查询参数类,用于表示条件参数对象 * @author Lixor(at)live.cn * */ public class Parameter{ private String field; private Object value; private String operator; /** * * @param field 数据库字段名 * @param operator 数据库操作符 =、>=、<、like etc... * @param value 参数值 Object */ public Parameter(String field,String operator, Object value) { super(); this.field = field; this.value = value; this.operator = operator; } public String getField() { return field; } public Object getValue() { return value; } public String getOperator() { return operator; } }
/** * 动态查询工具类,用于拼接SQL、填充pst * @author Lixor(at)live.cn * */ public class DynamicQuery { private static Logger logger=Logger.getLogger(DynamicQuery.class); private String templet = " AND %s %s ?"; private String baseSql; private ArrayList<Parameter> parameters = new ArrayList<Parameter>(); public DynamicQuery() { } /** * 要求baseSql带有where条件 * * @param baseSql */ public void setBaseSql(String baseSql) { this.baseSql = baseSql; } public void addParameter(Parameter parameter) { parameters.add(parameter); } public String generateSql() { StringBuffer buffer = new StringBuffer(baseSql); for (Parameter p : parameters) { buffer.append(String.format(templet, p.getField(), p.getOperator())); } logger.debug(buffer); return buffer.toString(); } public void fillPreparedStatement(PreparedStatement pst) throws SQLException { int count = 1; for (Parameter p : parameters) { pst.setObject(count, p.getValue()); count++; } } }
DynamicQuery query=new DynamicQuery(); query.addParameter(new Parameter("p.name" ,"like","电视")); query.addParameter(new Parameter("p.type_id","=" ,1)); query.addParameter(new Parameter("p.productDate" ,">=",java.sql.Date.valueOf("2010-09-04"))); query.addParameter(new Parameter("p.price" ,">=",1000.0f)); ProductDao dao=new ProductDao(); List<Product> productList=dao.query(query); request.setAttribute("productList",productList);
public List<Product> query(DynamicQuery query) { List<Product> productList = new ArrayList<Product>(); try { String sql = "SELECT p.id,p.name,p.price,p.productDate,p.image,p.type_id,t.name,p.description FROM tbl_product p,tbl_type t WHERE p.type_id=t.id"; query.setBaseSql(sql); sql = query.generateSql();//如果想排序,自行在sql后添加 Connection conn = null; try { conn = DbUtil.getConnection(); PreparedStatement pst= conn.prepareStatement(sql); query.fillPreparedStatement(pst);//填充pst ResultSet rs = pst.executeQuery(); while (rs.next()) { Product product = new Product(); …… productList.add(product); } rs.close(); pst.close(); } finally { if (conn != null) { conn.close();