Ticket #130: SqlBuilder.java

File SqlBuilder.java, 2.1 KB (added by chenchongqi, 13 years ago)
Line 
1/*
2 * To change this template, choose Tools | Templates
3 * and open the template in the editor.
4 */
5package cn.com.pconline.core.product.service;
6
7import java.util.ArrayList;
8import java.util.List;
9
10/**
11 *
12 * @author pc
13 */
14public class SqlBuilder {
15protected StringBuilder sqlBuf = new StringBuilder();
16    protected List values = new ArrayList();
17    protected boolean isFinished = false;
18
19    public SqlBuilder appendSql(String sql) {
20        checkFinished();
21        sqlBuf.append(sql);
22        return this;
23    }   
24
25    public SqlBuilder appendValue(Object value) {
26        checkFinished();
27        sqlBuf.append('?');
28        values.add(value);
29        return this;
30    }
31
32    public SqlBuilder appendValues(Object[] values) {
33        checkFinished();
34        sqlBuf.append('(');
35        for (int i = 0, c = values.length; i < c; ++i) {
36            sqlBuf.append('?').append(',');
37            this.values.add(values);
38        }
39        int last = sqlBuf.length() - 1;
40        if (last > 0 && sqlBuf.charAt(last) == ',') {
41            sqlBuf.setCharAt(last, ')');
42        }
43 
44        return this;
45    }
46
47    void checkFinished(){
48        if(isFinished){
49            throw new java.lang.IllegalStateException("Try to append a finished sql");
50        }
51    }
52   
53    public SqlBuilder page(int pageNo, int pageSize) {
54        int offset = (pageNo - 1) * pageSize;
55        int limit = pageSize;
56        sqlBuf.insert(1, "SELECT B.* FROM (SELECT A.*, rownum AS r__n FROM (");
57        sqlBuf.append(" ) A  ) B WHERE ");
58       
59        if (offset > 0) {
60            this.appendSql(" B.r__n > ").appendValue(offset);
61            if (limit > 0) {
62                this.appendSql(" AND B.r__n <= ").appendValue(offset + limit);
63            }
64        } else {
65            this.appendSql(" B.r__n <= ").appendValue(limit);
66        }
67        isFinished = true;
68        return this;
69    }
70
71    public String getSql() {
72        return sqlBuf.toString();
73    }
74
75    public Object[] getValues() {
76        return values.toArray();
77    }
78}