Common-dbutils 通用类的使用

dbutils通用类,dbutils分页查询,第一部分是公共类,封装好了操作数据库的方法。第二部分是分页的bean。

第一部分:

Java代码   收藏代码
  1. public class DBUtilsTemplate {  
  2.   
  3.     private DataSource dataSource;  
  4.     private QueryRunner queryRunner;  
  5.     private static final Log LOG = LogFactory.getLog(DBUtilsTemplate.class);  
  6.   
  7.     public DBUtilsTemplate(DataSource dataSources) {  
  8.         this();  
  9.     }  
  10.   
  11.     public DBUtilsTemplate() {  
  12.         dataSource = MyDataSource.getdataSource();  
  13.     }  
  14.   
  15.     /** 
  16.      *  
  17.      * @param sql 
  18.      *            插入sql语句 
  19.      * @param params 
  20.      *            插入参数 
  21.      * @return 返回影响行数 
  22.      */  
  23.     public int insert(String sql, Object[] params) {  
  24.         queryRunner = new QueryRunner(dataSource);  
  25.         int affectedRows = 0;  
  26.         try {  
  27.             if (params == null) {  
  28.                 affectedRows = queryRunner.update(sql);  
  29.             } else {  
  30.                 affectedRows = queryRunner.update(sql, params);  
  31.             }  
  32.         } catch (SQLException e) {  
  33.             e.printStackTrace();  
  34.             LOG.error("insert.插入记录错误:" + sql, e);  
  35.         }  
  36.         return affectedRows;  
  37.     }  
  38.   
  39.     /** 
  40.      * 插入数据库,返回自动增长的主键 
  41.      *  
  42.      * @param sql - 
  43.      *            执行的sql语句 
  44.      * @return 主键 注意;此方法没关闭资源 
  45.      */  
  46.     public int insertForKeys(String sql, Object[] params) {  
  47.         int key = 0;  
  48.         Connection conn = null;  
  49.         PreparedStatement stmt = null;  
  50.         ResultSet rs = null;  
  51.         try {  
  52.             conn = dataSource.getConnection();  
  53.             stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);  
  54.             ParameterMetaData pmd = stmt.getParameterMetaData();  
  55.             if (params.length < pmd.getParameterCount()) {  
  56.                 throw new SQLException("参数错误:" + pmd.getParameterCount());  
  57.             }  
  58.             for (int i = 0; i < params.length; i++) {  
  59.                 stmt.setObject(i + 1, params[i]);  
  60.             }  
  61.             stmt.executeUpdate();  
  62.             rs = stmt.getGeneratedKeys();  
  63.             if (rs.next()) {  
  64.                 key = rs.getInt(1);  
  65.             }  
  66.         } catch (SQLException e) {  
  67.             e.printStackTrace();  
  68.             LOG.error("insertForKey.插入返回主键错误:" + sql, e);  
  69.         } finally {  
  70.             if (rs != null) { // 关闭记录集  
  71.                 try {  
  72.                     rs.close();  
  73.                 } catch (SQLException e) {  
  74.                     e.printStackTrace();  
  75.                 }  
  76.             }  
  77.             if (stmt != null) { // 关闭声明  
  78.                 try {  
  79.                     stmt.close();  
  80.                 } catch (SQLException e) {  
  81.                     e.printStackTrace();  
  82.                 }  
  83.             }  
  84.             if (conn != null) { // 关闭连接对象  
  85.                 try {  
  86.                     conn.close();  
  87.                 } catch (SQLException e) {  
  88.                     e.printStackTrace();  
  89.                 }  
  90.             }  
  91.         }  
  92.         return key;  
  93.     }  
  94.   
  95.     private ScalarHandler scalarHandler = new ScalarHandler() {  
  96.         @Override  
  97.         public Object handle(ResultSet rs) throws SQLException {  
  98.             Object obj = super.handle(rs);  
  99.             if (obj instanceof BigInteger)  
  100.                 return ((BigInteger) obj).longValue();  
  101.             return obj;  
  102.         }  
  103.     };  
  104.   
  105.     public long count(String sql, Object... params) {  
  106.         Number num = 0;  
  107.         try {  
  108.             queryRunner = new QueryRunner(dataSource);  
  109.             if (params == null) {  
  110.                 num = (Number) queryRunner.query(sql, scalarHandler);  
  111.             } else {  
  112.                 num = (Number) queryRunner.query(sql, scalarHandler, params);  
  113.             }  
  114.         } catch (SQLException e) {  
  115.             e.printStackTrace();  
  116.             LOG.error("count.统计数量错误" + sql, e);  
  117.         }  
  118.         return (num != null) ? num.longValue() : -1;  
  119.     }  
  120.   
  121.     /** 
  122.      * 执行sql语句 
  123.      *  
  124.      * @param sql 
  125.      *            sql语句 
  126.      * @return 受影响的行数 
  127.      */  
  128.     public int update(String sql) {  
  129.         return update(sql, null);  
  130.     }  
  131.   
  132.     /** 
  133.      * 单条修改记录 
  134.      *  
  135.      * @param sql 
  136.      *            sql语句 
  137.      * @param param 
  138.      *            参数 
  139.      * @return 受影响的行数 
  140.      */  
  141.     public int update(String sql, Object param) {  
  142.         return update(sql, new Object[] { param });  
  143.     }  
  144.   
  145.     /** 
  146.      * 单条修改记录 
  147.      *  
  148.      * @param sql 
  149.      *            sql语句 
  150.      * @param params 
  151.      *            参数数组 
  152.      * @return 受影响的行数 
  153.      */  
  154.     public int update(String sql, Object[] params) {  
  155.         queryRunner = new QueryRunner(dataSource);  
  156.         int affectedRows = 0;  
  157.         try {  
  158.             if (params == null) {  
  159.                 affectedRows = queryRunner.update(sql);  
  160.             } else {  
  161.                 affectedRows = queryRunner.update(sql, params);  
  162.             }  
  163.         } catch (SQLException e) {  
  164.             e.printStackTrace();  
  165.             LOG.error("update.单条修改记录错误:" + sql, e);  
  166.         }  
  167.         return affectedRows;  
  168.     }  
  169.   
  170.     /** 
  171.      * 批量修改记录 
  172.      *  
  173.      * @param sql 
  174.      *            sql语句 
  175.      * @param params 
  176.      *            二维参数数组 
  177.      * @return 受影响的行数的数组 
  178.      */  
  179.     public int[] batchUpdate(String sql, Object[][] params) {  
  180.         queryRunner = new QueryRunner(dataSource);  
  181.         int[] affectedRows = new int[0];  
  182.         try {  
  183.             affectedRows = queryRunner.batch(sql, params);  
  184.         } catch (SQLException e) {  
  185.             e.printStackTrace();  
  186.             LOG.error("update.批量修改记录错误:" + sql, e);  
  187.         }  
  188.         return affectedRows;  
  189.     }  
  190.   
  191.     /** 
  192.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中 
  193.      *  
  194.      * @param sql 
  195.      *            sql语句 
  196.      * @return 查询结果 
  197.      */  
  198.     public List<Map<String, Object>> find(String sql) {  
  199.         return find(sql, null);  
  200.     }  
  201.   
  202.     /** 
  203.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中 
  204.      *  
  205.      * @param sql 
  206.      *            sql语句 
  207.      * @param param 
  208.      *            参数 
  209.      * @return 查询结果 
  210.      */  
  211.     public List<Map<String, Object>> find(String sql, Object param) {  
  212.         return find(sql, new Object[] { param });  
  213.     }  
  214.   
  215.     /** 
  216.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中 
  217.      *  
  218.      * @param sql 
  219.      *            sql语句 
  220.      * @param params 
  221.      *            参数数组 
  222.      * @return 查询结果 
  223.      */  
  224.     @SuppressWarnings("unchecked")  
  225.     public List<Map<String, Object>> findPage(String sql, int page, int count, Object... params) {  
  226.         sql = sql + " LIMIT ?,?";  
  227.         queryRunner = new QueryRunner(dataSource);  
  228.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  229.         try {  
  230.             if (params == null) {  
  231.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler(), new Integer[] { page,  
  232.                         count });  
  233.             } else {  
  234.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler(), ArrayUtils.addAll(  
  235.                         params, new Integer[] { page, count }));  
  236.             }  
  237.         } catch (SQLException e) {  
  238.             e.printStackTrace();  
  239.             LOG.error("map 数据分页查询错误", e);  
  240.         }  
  241.         return list;  
  242.     }  
  243.   
  244.     /** 
  245.      * 执行查询,将每行的结果保存到一个Map对象中,然后将所有Map对象保存到List中 
  246.      *  
  247.      * @param sql 
  248.      *            sql语句 
  249.      * @param params 
  250.      *            参数数组 
  251.      * @return 查询结果 
  252.      */  
  253.     @SuppressWarnings("unchecked")  
  254.     public List<Map<String, Object>> find(String sql, Object[] params) {  
  255.         queryRunner = new QueryRunner(dataSource);  
  256.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  257.         try {  
  258.             if (params == null) {  
  259.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler());  
  260.             } else {  
  261.                 list = (List<Map<String, Object>>) queryRunner.query(sql, new MapListHandler(), params);  
  262.             }  
  263.         } catch (SQLException e) {  
  264.             e.printStackTrace();  
  265.             LOG.error("map 数据查询错误", e);  
  266.         }  
  267.         return list;  
  268.     }  
  269.   
  270.     /** 
  271.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中 
  272.      *  
  273.      * @param entityClass 
  274.      *            类名 
  275.      * @param sql 
  276.      *            sql语句 
  277.      * @return 查询结果 
  278.      */  
  279.     public <T> List<T> find(Class<T> entityClass, String sql) {  
  280.         return find(entityClass, sql, null);  
  281.     }  
  282.   
  283.     /** 
  284.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中 
  285.      *  
  286.      * @param entityClass 
  287.      *            类名 
  288.      * @param sql 
  289.      *            sql语句 
  290.      * @param param 
  291.      *            参数 
  292.      * @return 查询结果 
  293.      */  
  294.     public <T> List<T> find(Class<T> entityClass, String sql, Object param) {  
  295.         return find(entityClass, sql, new Object[] { param });  
  296.     }  
  297.   
  298.     /** 
  299.      * 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中 
  300.      *  
  301.      * @param entityClass 
  302.      *            类名 
  303.      * @param sql 
  304.      *            sql语句 
  305.      * @param params 
  306.      *            参数数组 
  307.      * @return 查询结果 
  308.      */  
  309.     @SuppressWarnings("unchecked")  
  310.     public <T> List<T> find(Class<T> entityClass, String sql, Object[] params) {  
  311.         queryRunner = new QueryRunner(dataSource);  
  312.         List<T> list = new ArrayList<T>();  
  313.         try {  
  314.             if (params == null) {  
  315.                 list = (List<T>) queryRunner.query(sql, new BeanListHandler(entityClass));  
  316.             } else {  
  317.                 list = (List<T>) queryRunner.query(sql, new BeanListHandler(entityClass), params);  
  318.             }  
  319.         } catch (SQLException e) {  
  320.             e.printStackTrace();  
  321.             LOG.error("Error occured while attempting to query data", e);  
  322.         }  
  323.         return list;  
  324.     }  
  325.   
  326.     /** 
  327.      * 查询出结果集中的第一条记录,并封装成对象 
  328.      *  
  329.      * @param entityClass 
  330.      *            类名 
  331.      * @param sql 
  332.      *            sql语句 
  333.      * @return 对象 
  334.      */  
  335.     public <T> T findFirst(Class<T> entityClass, String sql) {  
  336.         return findFirst(entityClass, sql, null);  
  337.     }  
  338.   
  339.     /** 
  340.      * 查询出结果集中的第一条记录,并封装成对象 
  341.      *  
  342.      * @param entityClass 
  343.      *            类名 
  344.      * @param sql 
  345.      *            sql语句 
  346.      * @param param 
  347.      *            参数 
  348.      * @return 对象 
  349.      */  
  350.     public <T> T findFirst(Class<T> entityClass, String sql, Object param) {  
  351.         return findFirst(entityClass, sql, new Object[] { param });  
  352.     }  
  353.   
  354.     /** 
  355.      * 查询出结果集中的第一条记录,并封装成对象 
  356.      *  
  357.      * @param entityClass 
  358.      *            类名 
  359.      * @param sql 
  360.      *            sql语句 
  361.      * @param params 
  362.      *            参数数组 
  363.      * @return 对象 
  364.      */  
  365.     @SuppressWarnings("unchecked")  
  366.     public <T> T findFirst(Class<T> entityClass, String sql, Object[] params) {  
  367.         queryRunner = new QueryRunner(dataSource);  
  368.         Object object = null;  
  369.         try {  
  370.             if (params == null) {  
  371.                 object = queryRunner.query(sql, new BeanHandler(entityClass));  
  372.             } else {  
  373.                 object = queryRunner.query(sql, new BeanHandler(entityClass), params);  
  374.             }  
  375.         } catch (SQLException e) {  
  376.             LOG.error("返回一条记录错误:findFirst" + e.getMessage());  
  377.             e.printStackTrace();  
  378.         }  
  379.         return (T) object;  
  380.     }  
  381.   
  382.     /** 
  383.      * 查询出结果集中的第一条记录,并封装成Map对象 
  384.      *  
  385.      * @param sql 
  386.      *            sql语句 
  387.      * @return 封装为Map的对象 
  388.      */  
  389.     public Map<String, Object> findFirst(String sql) {  
  390.         return findFirst(sql, null);  
  391.     }  
  392.   
  393.     /** 
  394.      * 查询出结果集中的第一条记录,并封装成Map对象 
  395.      *  
  396.      * @param sql 
  397.      *            sql语句 
  398.      * @param param 
  399.      *            参数 
  400.      * @return 封装为Map的对象 
  401.      */  
  402.     public Map<String, Object> findFirst(String sql, Object param) {  
  403.         return findFirst(sql, new Object[] { param });  
  404.     }  
  405.   
  406.     /** 
  407.      * 查询出结果集中的第一条记录,并封装成Map对象 
  408.      *  
  409.      * @param sql 
  410.      *            sql语句 
  411.      * @param params 
  412.      *            参数数组 
  413.      * @return 封装为Map的对象 
  414.      */  
  415.     @SuppressWarnings("unchecked")  
  416.     public Map<String, Object> findFirst(String sql, Object[] params) {  
  417.         queryRunner = new QueryRunner(dataSource);  
  418.         Map<String, Object> map = null;  
  419.         try {  
  420.             if (params == null) {  
  421.                 map = (Map<String, Object>) queryRunner.query(sql, new MapHandler());  
  422.             } else {  
  423.                 map = (Map<String, Object>) queryRunner.query(sql, new MapHandler(), params);  
  424.             }  
  425.         } catch (SQLException e) {  
  426.             e.printStackTrace();  
  427.             LOG.error("findFirst.查询一条记录错误" + sql, e);  
  428.         }  
  429.         return map;  
  430.     }  
  431.   
  432.     /** 
  433.      * 查询某一条记录,并将指定列的数据转换为Object 
  434.      *  
  435.      * @param sql 
  436.      *            sql语句 
  437.      * @param columnName 
  438.      *            列名 
  439.      * @return 结果对象 
  440.      */  
  441.     public Object findBy(String sql, String params) {  
  442.         return findBy(sql, params, null);  
  443.     }  
  444.   
  445.     /** 
  446.      * 查询某一条记录,并将指定列的数据转换为Object 
  447.      *  
  448.      * @param sql 
  449.      *            sql语句 
  450.      * @param columnName 
  451.      *            列名 
  452.      * @param param 
  453.      *            参数 
  454.      * @return 结果对象 
  455.      */  
  456.     public Object findBy(String sql, String columnName, Object param) {  
  457.         return findBy(sql, columnName, new Object[] { param });  
  458.     }  
  459.   
  460.     /** 
  461.      * 查询某一条记录,并将指定列的数据转换为Object 
  462.      *  
  463.      * @param sql 
  464.      *            sql语句 
  465.      * @param columnName 
  466.      *            列名 
  467.      * @param params 
  468.      *            参数数组 
  469.      * @return 结果对象 
  470.      */  
  471.     public Object findBy(String sql, String columnName, Object[] params) {  
  472.         queryRunner = new QueryRunner(dataSource);  
  473.         Object object = null;  
  474.         try {  
  475.             if (params == null) {  
  476.                 object = queryRunner.query(sql, new ScalarHandler(columnName));  
  477.             } else {  
  478.                 object = queryRunner.query(sql, new ScalarHandler(columnName), params);  
  479.             }  
  480.         } catch (SQLException e) {  
  481.             e.printStackTrace();  
  482.             LOG.error("findBy。错误" + sql, e);  
  483.         }  
  484.         return object;  
  485.     }  
  486.   
  487.     /** 
  488.      * 查询某一条记录,并将指定列的数据转换为Object 
  489.      *  
  490.      * @param sql 
  491.      *            sql语句 
  492.      * @param columnIndex 
  493.      *            列索引 
  494.      * @return 结果对象 
  495.      */  
  496.     public Object findBy(String sql, int columnIndex) {  
  497.         return findBy(sql, columnIndex, null);  
  498.     }  
  499.   
  500.     /** 
  501.      * 查询某一条记录,并将指定列的数据转换为Object 
  502.      *  
  503.      * @param sql 
  504.      *            sql语句 
  505.      * @param columnIndex 
  506.      *            列索引 
  507.      * @param param 
  508.      *            参数 
  509.      * @return 结果对象 
  510.      */  
  511.     public Object findBy(String sql, int columnIndex, Object param) {  
  512.         return findBy(sql, columnIndex, new Object[] { param });  
  513.     }  
  514.   
  515.     /** 
  516.      * 查询某一条记录,并将指定列的数据转换为Object 
  517.      *  
  518.      * @param sql 
  519.      *            sql语句 
  520.      * @param columnIndex 
  521.      *            列索引 
  522.      * @param params 
  523.      *            参数数组 
  524.      * @return 结果对象 
  525.      */  
  526.     public Object findBy(String sql, int columnIndex, Object[] params) {  
  527.         queryRunner = new QueryRunner(dataSource);  
  528.         Object object = null;  
  529.         try {  
  530.             if (params == null) {  
  531.                 object = queryRunner.query(sql, new ScalarHandler(columnIndex));  
  532.             } else {  
  533.                 object = queryRunner.query(sql, new ScalarHandler(columnIndex), params);  
  534.             }  
  535.         } catch (SQLException e) {  
  536.             e.printStackTrace();  
  537.             LOG.error("findBy.错误" + sql, e);  
  538.         }  
  539.         return object;  
  540.     }  
  541.   
  542.     /** 
  543.      *  
  544.      * @param <T>分页查询 
  545.      * @param beanClass 
  546.      * @param sql 
  547.      * @param page 
  548.      * @param count 
  549.      * @param params 
  550.      * @return 
  551.      */  
  552.     public <T> List<T> findPage(Class<T> beanClass, String sql, int page, int pageSize, Object... params) {  
  553.         if (page <= 1) {  
  554.             page = 0;  
  555.         }  
  556.         return query(beanClass, sql + " LIMIT ?,?", ArrayUtils.addAll(params, new Integer[] { page, pageSize }));  
  557.     }  
  558.   
  559.     public <T> List<T> query(Class<T> beanClass, String sql, Object... params) {  
  560.         try {  
  561.             queryRunner = new QueryRunner(dataSource);  
  562.             return (List<T>) queryRunner.query(sql, isPrimitive(beanClass) ? columnListHandler : new BeanListHandler(  
  563.                     beanClass), params);  
  564.         } catch (SQLException e) {  
  565.             e.printStackTrace();  
  566.         }  
  567.         return null;  
  568.     }  
  569.   
  570.     private List<Class<?>> PrimitiveClasses = new ArrayList<Class<?>>() {  
  571.         {  
  572.             add(Long.class);  
  573.             add(Integer.class);  
  574.             add(String.class);  
  575.             add(java.util.Date.class);  
  576.             add(java.sql.Date.class);  
  577.             add(java.sql.Timestamp.class);  
  578.         }  
  579.     };  
  580.     // 返回单一列时用到的handler  
  581.     private final static ColumnListHandler columnListHandler = new ColumnListHandler() {  
  582.         @Override  
  583.         protected Object handleRow(ResultSet rs) throws SQLException {  
  584.             Object obj = super.handleRow(rs);  
  585.             if (obj instanceof BigInteger)  
  586.                 return ((BigInteger) obj).longValue();  
  587.             return obj;  
  588.         }  
  589.   
  590.     };  
  591.   
  592.     // 判断是否为原始类型  
  593.     private boolean isPrimitive(Class<?> cls) {  
  594.         return cls.isPrimitive() || PrimitiveClasses.contains(cls);  
  595.     }  
  596.     // map  
  597.   
  598. }  

 

第二部分:

Java代码   收藏代码
  1. public class PageHelp {  
  2.     private int pageSize;  
  3.     private int totalCount;  
  4.     private int currentPage;  
  5.     private int startIndex;  
  6.     private int[] indexes = new int[0];  
  7.     private int nextIndex;  
  8.     private int previousIndex;  
  9.     private int pageCount;  
  10.     private List items;  
  11.     private int lastIndex;  
  12.     private String currentUrl;  
  13.   
  14.     public String getCurrentUrl() {  
  15.         return currentUrl;  
  16.     }  
  17.   
  18.     public void setCurrentUrl(String currentUrl) {  
  19.         this.currentUrl = currentUrl;  
  20.     }  
  21.   
  22.     public PageHelp(List items, int totalCount, int startIndex) {  
  23.         pageSize = Constants.PAGE_SIZE;  
  24.         setPageSize(pageSize);  
  25.         setTotalCount(totalCount);  
  26.         setItems(items);  
  27.         setStartIndex(startIndex);  
  28.   
  29.     }  
  30.   
  31.     public void setTotalCount(int totalCount) {  
  32.         if (totalCount > 0) {  
  33.             this.totalCount = totalCount;  
  34.             int count = totalCount / pageSize;  
  35.             if (totalCount % pageSize > 0) {  
  36.                 count++;  
  37.             }  
  38.             indexes = new int[count];  
  39.             for (int i = 0; i < count; i++) {  
  40.                 indexes[i] = pageSize * i;  
  41.             }  
  42.         } else {  
  43.             this.totalCount = 0;  
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      * 得到总记录数 
  49.      *  
  50.      * @return 
  51.      */  
  52.     public int getTotalCount() {  
  53.         return totalCount;  
  54.     }  
  55.   
  56.     public void setIndexes(int[] indexes) {  
  57.         this.indexes = indexes;  
  58.     }  
  59.   
  60.     /** 
  61.      * 得到分页索引的数组 
  62.      *  
  63.      * @return 
  64.      */  
  65.     public int[] getIndexes() {  
  66.         return indexes;  
  67.     }  
  68.   
  69.     public void setStartIndex(int startIndex) {  
  70.         if (totalCount <= 0) {  
  71.             this.startIndex = 0;  
  72.         } else if (startIndex >= totalCount) {  
  73.             this.startIndex = indexes[indexes.length - 1];  
  74.         } else if (startIndex < 0) {  
  75.             this.startIndex = 0;  
  76.         } else {  
  77.             this.startIndex = indexes[startIndex / pageSize];  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      * 当前页 
  83.      *  
  84.      * @return 
  85.      */  
  86.     public int getStartIndex() {  
  87.         return startIndex;  
  88.     }  
  89.   
  90.     public void setNextIndex(int nextIndex) {  
  91.         this.nextIndex = nextIndex;  
  92.     }  
  93.   
  94.     /** 
  95.      * 下一页 
  96.      *  
  97.      * @return 
  98.      */  
  99.     public int getNextIndex() {  
  100.         int nextIndex = getStartIndex() + pageSize;  
  101.         if (nextIndex >= totalCount) {  
  102.             return getStartIndex();  
  103.         } else {  
  104.             return nextIndex;  
  105.         }  
  106.     }  
  107.   
  108.     public void setPreviousIndex(int previousIndex) {  
  109.         this.previousIndex = previousIndex;  
  110.     }  
  111.   
  112.     /** 
  113.      * 上一页 
  114.      *  
  115.      * @return 
  116.      */  
  117.     public int getPreviousIndex() {  
  118.         int previousIndex = getStartIndex() - pageSize;  
  119.         if (previousIndex < 0) {  
  120.             return 0;  
  121.         } else {  
  122.             return previousIndex;  
  123.         }  
  124.     }  
  125.   
  126.     public void setPageCount(int pageCount) {  
  127.         this.pageCount = pageCount;  
  128.     }  
  129.   
  130.     public int getPageCount() {  
  131.         int count = totalCount / pageSize;  
  132.         if (totalCount % pageSize > 0)  
  133.             count++;  
  134.         return count;  
  135.     }  
  136.   
  137.     public int getCurrentPage() {  
  138.         return getStartIndex() / pageSize + 1;  
  139.     }  
  140.   
  141.     public void setCurrentPage(int currentPage) {  
  142.         this.currentPage = currentPage;  
  143.     }  
  144.   
  145.     public void setLastIndex(int lastIndex) {  
  146.         this.lastIndex = lastIndex;  
  147.     }  
  148.   
  149.     public int getLastIndex() {  
  150.         if (indexes.length == 0) {  
  151.             return 0;  
  152.         } else {  
  153.             return indexes[indexes.length - 1];  
  154.         }  
  155.     }  
  156.   
  157.     public int getPageSize() {  
  158.         return pageSize;  
  159.     }  
  160.   
  161.     public void setPageSize(int pageSize) {  
  162.         this.pageSize = pageSize;  
  163.     }  
  164.   
  165.     /** 
  166.      * 得到已分页好的结果集 
  167.      *  
  168.      * @return 
  169.      */  
  170.     public List getItems() {  
  171.         return items;  
  172.     }  
  173.   
  174.     public void setItems(List items) {  
  175.         this.items = items;  
  176.     }  

 

 

使用方法:

 

考虑到分层的话可以这样使用:

Java代码   收藏代码
  1. public class CommonDaoImpl extends DBUtilsTemplate implements CommonDao   

 

还可以直接new  DBUtilsTemplate () 使用。

 

分页使用方法:

 

Java代码   收藏代码
  1. //(String sql, int page, int count, Object... params);    
  2. List list= ucd.findPage(sql, p, Constants.PAGE_SIZE, "y");  
  3. int totalRows=总记录数  
  4. return new PageHelp(list, totalRows, p);  

 

在jsp中显示分页方法:

 

 

Java代码   收藏代码
  1. <table width="100%" border="0" align="center" cellpadding="0"  
  2.                         cellspacing="0">  
  3.                         <tr align="center">  
  4.                             <td>  
  5.                                 <a href="${pageList.currentUrl}&page=0">第一页</a>&nbsp;&nbsp;&nbsp;&nbsp;  
  6.                                 <a href="${pageList.currentUrl}&page=${pageList.previousIndex}">上一页</a>&nbsp;&nbsp;&nbsp;&nbsp;  
  7.                                 <c:forEach items="${pageList.indexes}" var="itempage"  
  8.                                     varStatus="stuts">  
  9.                                     <c:choose>  
  10.                                         <c:when test="${pageList.currentPage ==stuts.index+1}">  
  11.                                             <a style="color: red"> ${stuts.index+1}</a>  
  12.                                         </c:when>  
  13.                                         <c:otherwise>  
  14.                                         </c:otherwise>  
  15.                                     </c:choose>  
  16.                                 </c:forEach>  
  17.                                 &nbsp;&nbsp;&nbsp;&nbsp;  
  18.                                 <a href="${pageList.currentUrl}&page=${pageList.nextIndex}">  
  19.                                     下一页</a> &nbsp;&nbsp;&nbsp;&nbsp;  
  20.                                 <a href="${pageList.currentUrl}&page=${pageList.lastIndex}">最后页</a>  
  21.                                 &nbsp;&nbsp;&nbsp;&nbsp;总数: ${ pageList.totalCount}  
  22.                                 &nbsp;&nbsp;&nbsp;&nbsp;总页数: ${ pageList.pageCount}  
  23.                             </td>  
  24.                         </tr>  
  25.                     </table>  

 

解释:currentUrl  是在action中 获取PageHelp 对象后,对他的属性currentUrl  重新赋值(即:当前请求url)

 

放上去一个效果图吧:

dbutils通用类,dbutils分页查询

 

 

 补充:数据源,使用的是dbcp

 

Java代码   收藏代码
  1. public class MyDataSource {  
  2.     private static Properties properties;  
  3.     private static DataSource dataSource;  
  4.     static {  
  5.         try {  
  6.             properties = new Properties();  
  7.             properties.load(MyDataSource.class.getResourceAsStream("/dbcpconfig.properties"));  
  8.             BasicDataSourceFactory b = new BasicDataSourceFactory();  
  9.             dataSource = b.createDataSource(properties);  
  10.         } catch (Exception e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.     }  
  14.   
  15.     public static DataSource getdataSource() {  
  16.         return dataSource;  
  17.     }  
  18. }  

 

 数据源配置文件:

 

Java代码   收藏代码
  1. #连接设置  
  2. driverClassName=com.mysql.jdbc.Driver  
  3. url=jdbc:mysql://localhost:3306/cc  
  4. username=root  
  5. password=cc  
  6. #初始化连接  
  7. initialSize=5  
  8.   
  9. #最大连接数量  
  10. maxActive=40  
  11.   
  12. #最大空闲连接  
  13. maxIdle=20  
  14.   
  15. #最小空闲连接  
  16. minIdle=5  
  17.   
  18. #超时等待时间以毫秒为单位 6000毫秒/1000等于60秒  
  19. maxWait=10000  
  20.   
  21.   
  22. #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]   
  23. #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。  
  24. connectionProperties=useUnicode=true;characterEncoding=UTF-8  
  25.   
  26. #指定由连接池所创建的连接的自动提交(auto-commit)状态。  
  27. defaultAutoCommit=true  
  28.   
  29. #driver default 指定由连接池所创建的连接的只读(read-only)状态。  
  30. #如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)  
  31. defaultReadOnly=  
  32. #是否自动回收超时连接(一般是忘了释放的)  
  33. removeAbandoned=true  
  34. # 将被遗弃的数据库连接的回收记入日志。    
  35. logAbandoned=true  
  36. # 数据库连接过多长时间不用将被视为被遗弃而收回连接池中。  
  37. removeAbandonedTimeout=30  
  38. #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。  
  39. #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE  
  40. #defaultTransactionIsolation=REPEATABLE_READ  
  41. #db.pool.default.whenExhaustedAction=grow  
  42. #新增参数,用于8小时问题  
  43. testOnBorrow=true  
  44. testOnReturn=false  
  45. testWhileIdle=true  
  46. validationQuery=select 1  

猜你喜欢

转载自kiss-man.iteye.com/blog/2245782
今日推荐