今日学习-商品数据库查询

在学习到数据库高级查询这里,看到一些好的方法,做一些记录,每天都积累一些,进步一点

首先,我定义了一个规范(接口)

1 //定义一种规范,让所有查询的对象,都来实现这个接口
2 public interface IQuery {
3     //返回拼接好的查询条件语句
4     String getQuary();
5     //返回getQuery方法拼接sql占位符对应的参数
6     List<Object> getparmeters();    
7 }

接着,给这个接口添加一个实现类,也称作查询类的基类,以后的查询对象,只要继承这个父类,就可以做出自己的查询结果

 1 //查询类的基类
 2 public class QueryObject implements IQuery{
 3     //使用list来封装查询条件   
 4     private List<String> condition = new ArrayList<>();
 5     //使用list来封装查询的参数 (list允许元素元素重复且无序)
 6     private List<Object> paramters = new ArrayList<>();
 7     //把查寻的sql语句放在这里面
 8     public String getQuary() {
 9         StringBuilder sql = new StringBuilder(200);
10         //商品分类的商品名称
11         this.customizedQuery();
12         for (int i = 0; i < condition.size(); i++) {
13             if (i == 0) {
14                 sql.append(" WHERE ");
15             }else{
16                 sql.append(" AND ");
17             }
18             sql.append(condition.get(i));
19         }
20         return sql.toString();
21     }
22 
23     public List<Object> getparmeters() {
24         return this.paramters;
25     }
26     //专门用来给子类自己去实现,添加自身查询信息的方法
27     protected void customizedQuery() {
28         
29     }
30     //专门暴漏给子类,让子类添加自身的查询条件和参数
31     protected void addQuery(String condition,Object param){
32         this.condition.add(condition);
33         this.paramters.add(param);
34     }
35 }

子类在继承父类后,只需要实现父类中的customizedQuery();这个方法,其他不用关心,并且在查询中,也只需要去关心查询条件和查询的参数即可

 1 //子类继承父类,在子类中查询具体的信息操作,自身对象的定制查询
 2     public void customizedQuery() {
 3         //商品名称
 4         if (StringUtil.hasLength(name)) {
 5             super.addQuery("productName LIKE ?", "%" + name + "%");
 6         }
 7         if (minSalePrice != null) {//最低零售价
 8             super.addQuery("salePrice >= ?", minSalePrice);
 9         }
10         if (maxSalePrice != null) {//最高零售价
11             super.addQuery("salePrice <= ?", maxSalePrice);
12         }
13         //必须先做非空判断,在做等值判断
14         if (dirId != null && dirId != -1) {
15             super.addQuery("dir_id = ?", dirId);
16         }
17         
18         /* 下面的那个就是错误的例子  会导致空指针异常
19          * 
20          * if (dirId != -1 && dirId != null) {
21             super.addQuery("dir_id = ?", dirId);
22         }*/
23     }

在商品DAO查询的实现类里

 1 /**
 2      * ProductQueryObject - 继承父类QueryObject的子类 
 3      * sql- 查询的语句
 4      * rsh - 查询的结果集对象
 5      * 
 6      */
 7     public List<Product> query4(ProductQueryObject qo) {
 8         String sql = "SELECT * FROM product"+qo.getQuary();
 9         return JdbcTemplate.quary(sql,rsh, qo.getparmeters().toArray() );
10     }
原文地址:https://www.cnblogs.com/llynic/p/6196150.html