Java 之 JDBC:(七)DAO及相关实现类

一、DAO 及相关实现类

  DAO:Data Access Object 访问数据信息的类和接口,包括了对数据的CRUD(Create、Retrival,Update,Delete),而不包含任何业务相关的信息,有时也称作:BaseDAO。

  作用:为了实现功能的模块化,更有利于代码的维护和升级。

  项目中案例:

  

   层次结构:

  

二、版本一

  1、BaseDAO

    封装了针对于数据表的通用的操作。

    代码实现:

  1 /**
  2  * DAO: data(base) access object
  3  * 封装了针对于数据表的通用的操作
  4  */
  5 public abstract class BaseDAO {
  6     // 通用的增删改操作---version 2.0 (考虑上事务)
  7     public int update(Connection conn, String sql, Object... args) {// sql中占位符的个数与可变形参的长度相同!
  8         PreparedStatement ps = null;
  9         try {
 10             // 1.预编译sql语句,返回PreparedStatement的实例
 11             ps = conn.prepareStatement(sql);
 12             // 2.填充占位符
 13             for (int i = 0; i < args.length; i++) {
 14                 ps.setObject(i + 1, args[i]);// 小心参数声明错误!!
 15             }
 16             // 3.执行
 17             return ps.executeUpdate();
 18         } catch (Exception e) {
 19             e.printStackTrace();
 20         } finally {
 21             // 4.资源的关闭
 22             JDBCUtils.closeResource(null, ps);
 23 
 24         }
 25         return 0;
 26 
 27     }
 28 
 29     // 通用的查询操作,用于返回数据表中的一条记录(version 2.0:考虑上事务)
 30     public <T> T getInstance(Connection conn, Class<T> clazz, String sql, Object... args) {
 31         PreparedStatement ps = null;
 32         ResultSet rs = null;
 33         try {
 34 
 35             ps = conn.prepareStatement(sql);
 36             for (int i = 0; i < args.length; i++) {
 37                 ps.setObject(i + 1, args[i]);
 38             }
 39 
 40             rs = ps.executeQuery();
 41             // 获取结果集的元数据 :ResultSetMetaData
 42             ResultSetMetaData rsmd = rs.getMetaData();
 43             // 通过ResultSetMetaData获取结果集中的列数
 44             int columnCount = rsmd.getColumnCount();
 45 
 46             if (rs.next()) {
 47                 T t = clazz.newInstance();
 48                 // 处理结果集一行数据中的每一个列
 49                 for (int i = 0; i < columnCount; i++) {
 50                     // 获取列值
 51                     Object columValue = rs.getObject(i + 1);
 52 
 53                     // 获取每个列的列名
 54                     // String columnName = rsmd.getColumnName(i + 1);
 55                     String columnLabel = rsmd.getColumnLabel(i + 1);
 56 
 57                     // 给t对象指定的columnName属性,赋值为columValue:通过反射
 58                     Field field = clazz.getDeclaredField(columnLabel);
 59                     field.setAccessible(true);
 60                     field.set(t, columValue);
 61                 }
 62                 return t;
 63             }
 64         } catch (Exception e) {
 65             e.printStackTrace();
 66         } finally {
 67             JDBCUtils.closeResource(null, ps, rs);
 68 
 69         }
 70 
 71         return null;
 72     }
 73     // 通用的查询操作,用于返回数据表中的多条记录构成的集合(version 2.0:考虑上事务)
 74     public <T> List<T> getForList(Connection conn, Class<T> clazz, String sql, Object... args) {
 75         PreparedStatement ps = null;
 76         ResultSet rs = null;
 77         try {
 78 
 79             ps = conn.prepareStatement(sql);
 80             for (int i = 0; i < args.length; i++) {
 81                 ps.setObject(i + 1, args[i]);
 82             }
 83 
 84             rs = ps.executeQuery();
 85             // 获取结果集的元数据 :ResultSetMetaData
 86             ResultSetMetaData rsmd = rs.getMetaData();
 87             // 通过ResultSetMetaData获取结果集中的列数
 88             int columnCount = rsmd.getColumnCount();
 89             // 创建集合对象
 90             ArrayList<T> list = new ArrayList<T>();
 91             while (rs.next()) {
 92                 T t = clazz.newInstance();
 93                 // 处理结果集一行数据中的每一个列:给t对象指定的属性赋值
 94                 for (int i = 0; i < columnCount; i++) {
 95                     // 获取列值
 96                     Object columValue = rs.getObject(i + 1);
 97 
 98                     // 获取每个列的列名
 99                     // String columnName = rsmd.getColumnName(i + 1);
100                     String columnLabel = rsmd.getColumnLabel(i + 1);
101 
102                     // 给t对象指定的columnName属性,赋值为columValue:通过反射
103                     Field field = clazz.getDeclaredField(columnLabel);
104                     field.setAccessible(true);
105                     field.set(t, columValue);
106                 }
107                 list.add(t);
108             }
109 
110             return list;
111         } catch (Exception e) {
112             e.printStackTrace();
113         } finally {
114             JDBCUtils.closeResource(null, ps, rs);
115 
116         }
117 
118         return null;
119     }
120     //用于查询特殊值的通用的方法
121     public <E> E getValue(Connection conn,String sql,Object...args){
122         PreparedStatement ps = null;
123         ResultSet rs = null;
124         try {
125             ps = conn.prepareStatement(sql);
126             for(int i = 0;i < args.length;i++){
127                 ps.setObject(i + 1, args[i]);
128                 
129             }
130             
131             rs = ps.executeQuery();
132             if(rs.next()){
133                 return (E) rs.getObject(1);
134             }
135         } catch (SQLException e) {
136             e.printStackTrace();
137         }finally{
138             JDBCUtils.closeResource(null, ps, rs);
139             
140         }
141         return null;
142         
143     }    
144 }

  2、CustomerDAO

    此接口用于规范针对于customers表的常用操作

    代码实现:

 1 /**
 2  * 此接口用于规范针对于customers表的常用操作
 3  */
 4 public interface CustomerDAO {
 5     /**
 6      * 
 7      * @Description 将cust对象添加到数据库中
 8      * @param conn
 9      * @param cust
10      */
11     void insert(Connection conn, Customer cust);
12     /**
13      * 
14      * @Description 针对指定的id,删除表中的一条记录
15      * @param conn
16      * @param id
17      */
18     void deleteById(Connection conn,int id);
19     /**
20      * 
21      * @Description 针对内存中的cust对象,去修改数据表中指定的记录
22      * @param conn
23      * @param cust
24      */
25     void update(Connection conn,Customer cust);
26     /**
27      * 
28      * @Description 针对指定的id查询得到对应的Customer对象
29      * @param conn
30      * @param id
31      */
32     Customer getCustomerById(Connection conn,int id);
33     /**
34      * 
35      * @Description 查询表中的所有记录构成的集合
36      * @param conn
37      * @return
38      */
39     List<Customer> getAll(Connection conn);
40     /**
41      * 
42      * @Description 返回数据表中的数据的条目数
43      * @param conn
44      * @return
45      */
46     Long getCount(Connection conn);
47     
48     /**
49      * 
50      * @Description 返回数据表中最大的生日
51      * @param conn
52      * @return
53      */
54     Date getMaxBirth(Connection conn);
55     
56 }

  3、CustomerDAOImpl

    具体的 Dao 实现类:

 1 public class CustomerDAOImpl extends BaseDAO implements CustomerDAO{
 2 
 3     @Override
 4     public void insert(Connection conn, Customer cust) {
 5         String sql = "insert into customers(name,email,birth)values(?,?,?)";
 6         update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth());
 7     }
 8 
 9     @Override
10     public void deleteById(Connection conn, int id) {
11         String sql = "delete from customers where id = ?";
12         update(conn, sql, id);
13     }
14 
15     @Override
16     public void update(Connection conn, Customer cust) {
17         String sql = "update customers set name = ?,email = ?,birth = ? where id = ?";
18         update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth(),cust.getId());
19     }
20 
21     @Override
22     public Customer getCustomerById(Connection conn, int id) {
23         String sql = "select id,name,email,birth from customers where id = ?";
24         Customer customer = getInstance(conn,Customer.class, sql,id);
25         return customer;
26     }
27 
28     @Override
29     public List<Customer> getAll(Connection conn) {
30         String sql = "select id,name,email,birth from customers";
31         List<Customer> list = getForList(conn, Customer.class, sql);
32         return list;
33     }
34 
35     @Override
36     public Long getCount(Connection conn) {
37         String sql = "select count(*) from customers";
38         return getValue(conn, sql);
39     }
40 
41     @Override
42     public Date getMaxBirth(Connection conn) {
43         String sql = "select max(birth) from customers";
44         return getValue(conn, sql);
45     }
46 
47 }

三、版本二

  1、BaseDAO

  1 /**
  2  * DAO: data(base) access object
  3  * 封装了针对于数据表的通用的操作
  4  */
  5 public abstract class BaseDAO<T> {
  6     
  7     private Class<T> clazz = null;
  8 
  9     
 10     {    
 11         //获取当前BaseDAO的子类继承的父类中的泛型
 12         Type genericSuperclass = this.getClass().getGenericSuperclass();
 13         ParameterizedType paramType = (ParameterizedType) genericSuperclass;
 14         
 15         Type[] typeArguments = paramType.getActualTypeArguments();//获取了父类的泛型参数
 16         clazz = (Class<T>) typeArguments[0];//泛型的第一个参数
 17         
 18     }
 19     
 20     
 21     // 通用的增删改操作---version 2.0 (考虑上事务)
 22     public int update(Connection conn, String sql, Object... args) {// sql中占位符的个数与可变形参的长度相同!
 23         PreparedStatement ps = null;
 24         try {
 25             // 1.预编译sql语句,返回PreparedStatement的实例
 26             ps = conn.prepareStatement(sql);
 27             // 2.填充占位符
 28             for (int i = 0; i < args.length; i++) {
 29                 ps.setObject(i + 1, args[i]);// 小心参数声明错误!!
 30             }
 31             // 3.执行
 32             return ps.executeUpdate();
 33         } catch (Exception e) {
 34             e.printStackTrace();
 35         } finally {
 36             // 4.资源的关闭
 37             JDBCUtils.closeResource(null, ps);
 38 
 39         }
 40         return 0;
 41 
 42     }
 43 
 44     // 通用的查询操作,用于返回数据表中的一条记录(version 2.0:考虑上事务)
 45     public T getInstance(Connection conn, String sql, Object... args) {
 46         PreparedStatement ps = null;
 47         ResultSet rs = null;
 48         try {
 49 
 50             ps = conn.prepareStatement(sql);
 51             for (int i = 0; i < args.length; i++) {
 52                 ps.setObject(i + 1, args[i]);
 53             }
 54 
 55             rs = ps.executeQuery();
 56             // 获取结果集的元数据 :ResultSetMetaData
 57             ResultSetMetaData rsmd = rs.getMetaData();
 58             // 通过ResultSetMetaData获取结果集中的列数
 59             int columnCount = rsmd.getColumnCount();
 60 
 61             if (rs.next()) {
 62                 T t = clazz.newInstance();
 63                 // 处理结果集一行数据中的每一个列
 64                 for (int i = 0; i < columnCount; i++) {
 65                     // 获取列值
 66                     Object columValue = rs.getObject(i + 1);
 67 
 68                     // 获取每个列的列名
 69                     // String columnName = rsmd.getColumnName(i + 1);
 70                     String columnLabel = rsmd.getColumnLabel(i + 1);
 71 
 72                     // 给t对象指定的columnName属性,赋值为columValue:通过反射
 73                     Field field = clazz.getDeclaredField(columnLabel);
 74                     field.setAccessible(true);
 75                     field.set(t, columValue);
 76                 }
 77                 return t;
 78             }
 79         } catch (Exception e) {
 80             e.printStackTrace();
 81         } finally {
 82             JDBCUtils.closeResource(null, ps, rs);
 83 
 84         }
 85 
 86         return null;
 87     }
 88     // 通用的查询操作,用于返回数据表中的多条记录构成的集合(version 2.0:考虑上事务)
 89     public List<T> getForList(Connection conn, String sql, Object... args) {
 90         PreparedStatement ps = null;
 91         ResultSet rs = null;
 92         try {
 93 
 94             ps = conn.prepareStatement(sql);
 95             for (int i = 0; i < args.length; i++) {
 96                 ps.setObject(i + 1, args[i]);
 97             }
 98 
 99             rs = ps.executeQuery();
100             // 获取结果集的元数据 :ResultSetMetaData
101             ResultSetMetaData rsmd = rs.getMetaData();
102             // 通过ResultSetMetaData获取结果集中的列数
103             int columnCount = rsmd.getColumnCount();
104             // 创建集合对象
105             ArrayList<T> list = new ArrayList<T>();
106             while (rs.next()) {
107                 T t = clazz.newInstance();
108                 // 处理结果集一行数据中的每一个列:给t对象指定的属性赋值
109                 for (int i = 0; i < columnCount; i++) {
110                     // 获取列值
111                     Object columValue = rs.getObject(i + 1);
112 
113                     // 获取每个列的列名
114                     // String columnName = rsmd.getColumnName(i + 1);
115                     String columnLabel = rsmd.getColumnLabel(i + 1);
116 
117                     // 给t对象指定的columnName属性,赋值为columValue:通过反射
118                     Field field = clazz.getDeclaredField(columnLabel);
119                     field.setAccessible(true);
120                     field.set(t, columValue);
121                 }
122                 list.add(t);
123             }
124 
125             return list;
126         } catch (Exception e) {
127             e.printStackTrace();
128         } finally {
129             JDBCUtils.closeResource(null, ps, rs);
130 
131         }
132 
133         return null;
134     }
135     //用于查询特殊值的通用的方法
136     public <E> E getValue(Connection conn,String sql,Object...args){
137         PreparedStatement ps = null;
138         ResultSet rs = null;
139         try {
140             ps = conn.prepareStatement(sql);
141             for(int i = 0;i < args.length;i++){
142                 ps.setObject(i + 1, args[i]);
143                 
144             }
145             
146             rs = ps.executeQuery();
147             if(rs.next()){
148                 return (E) rs.getObject(1);
149             }
150         } catch (SQLException e) {
151             e.printStackTrace();
152         }finally{
153             JDBCUtils.closeResource(null, ps, rs);
154             
155         }
156         return null;
157         
158     }    
159 }

  2、CustomerDAO

 1 /**
 2  * 此接口用于规范针对于customers表的常用操作
 3  */
 4 public interface CustomerDAO {
 5     /**
 6      * 
 7      * @Description 将cust对象添加到数据库中
 8      * @param conn
 9      * @param cust
10      */
11     void insert(Connection conn, Customer cust);
12     /**
13      * 
14      * @Description 针对指定的id,删除表中的一条记录
15      * @param conn
16      * @param id
17      */
18     void deleteById(Connection conn,int id);
19     /**
20      * 
21      * @Description 针对内存中的cust对象,去修改数据表中指定的记录
22      * @param conn
23      * @param cust
24      */
25     void update(Connection conn,Customer cust);
26     /**
27      * 
28      * @Description 针对指定的id查询得到对应的Customer对象
29      * @param conn
30      * @param id
31      */
32     Customer getCustomerById(Connection conn,int id);
33     /**
34      * 
35      * @Description 查询表中的所有记录构成的集合
36      * @param conn
37      * @return
38      */
39     List<Customer> getAll(Connection conn);
40     /**
41      * 
42      * @Description 返回数据表中的数据的条目数
43      * @param conn
44      * @return
45      */
46     Long getCount(Connection conn);
47     
48     /**
49      * 
50      * @Description 返回数据表中最大的生日
51      * @param conn
52      * @return
53      */
54     Date getMaxBirth(Connection conn);
55     
56 }    

  3、CustomerDAOImpl

 1 public class CustomerDAOImpl extends BaseDAO<Customer> implements CustomerDAO{
 2     
 3     
 4     @Override
 5     public void insert(Connection conn, Customer cust) {
 6         String sql = "insert into customers(name,email,birth)values(?,?,?)";
 7         update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth());
 8     }
 9 
10     @Override
11     public void deleteById(Connection conn, int id) {
12         String sql = "delete from customers where id = ?";
13         update(conn, sql, id);
14     }
15 
16     @Override
17     public void update(Connection conn, Customer cust) {
18         String sql = "update customers set name = ?,email = ?,birth = ? where id = ?";
19         update(conn, sql,cust.getName(),cust.getEmail(),cust.getBirth(),cust.getId());
20     }
21 
22     @Override
23     public Customer getCustomerById(Connection conn, int id) {
24         String sql = "select id,name,email,birth from customers where id = ?";
25         Customer customer = getInstance(conn, sql,id);
26         return customer;
27     }
28 
29     @Override
30     public List<Customer> getAll(Connection conn) {
31         String sql = "select id,name,email,birth from customers";
32         List<Customer> list = getForList(conn, sql);
33         return list;
34     }
35 
36     @Override
37     public Long getCount(Connection conn) {
38         String sql = "select count(*) from customers";
39         return getValue(conn, sql);
40     }
41 
42     @Override
43     public Date getMaxBirth(Connection conn) {
44         String sql = "select max(birth) from customers";
45         return getValue(conn, sql);
46     }
47 
48 }

四、版本三

  1、BaseDAO

 1 /**
 2  * 定义一个用来被继承的对数据库进行基本操作的Dao
 3  * 
 4  * @param <T>
 5  */
 6 public abstract class BaseDao<T> {
 7     private QueryRunner queryRunner = new QueryRunner();
 8     // 定义一个变量来接收泛型的类型
 9     private Class<T> type;
10 
11     // 获取T的Class对象,获取泛型的类型,泛型是在被子类继承时才确定
12     public BaseDao() {
13         // 获取子类的类型
14         Class clazz = this.getClass();
15         // 获取父类的类型
16         // getGenericSuperclass()用来获取当前类的父类的类型
17         // ParameterizedType表示的是带泛型的类型
18         ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
19         // 获取具体的泛型类型 getActualTypeArguments获取具体的泛型的类型
20         // 这个方法会返回一个Type的数组
21         Type[] types = parameterizedType.getActualTypeArguments();
22         // 获取具体的泛型的类型·
23         this.type = (Class<T>) types[0];
24     }
25 
26     /**
27      * 通用的增删改操作
28      * 
29      * @param sql
30      * @param params
31      * @return
32      */
33     public int update(Connection conn,String sql, Object... params) {
34         int count = 0;
35         try {
36             count = queryRunner.update(conn, sql, params);
37         } catch (SQLException e) {
38             e.printStackTrace();
39         } 
40         return count;
41     }
42 
43     /**
44      * 获取一个对象
45      * 
46      * @param sql
47      * @param params
48      * @return
49      */
50     public T getBean(Connection conn,String sql, Object... params) {
51         T t = null;
52         try {
53             t = queryRunner.query(conn, sql, new BeanHandler<T>(type), params);
54         } catch (SQLException e) {
55             e.printStackTrace();
56         } 
57         return t;
58     }
59 
60     /**
61      * 获取所有对象
62      * 
63      * @param sql
64      * @param params
65      * @return
66      */
67     public List<T> getBeanList(Connection conn,String sql, Object... params) {
68         List<T> list = null;
69         try {
70             list = queryRunner.query(conn, sql, new BeanListHandler<T>(type), params);
71         } catch (SQLException e) {
72             e.printStackTrace();
73         } 
74         return list;
75     }
76 
77     /**
78      * 获取一个但一值得方法,专门用来执行像 select count(*)...这样的sql语句
79      * 
80      * @param sql
81      * @param params
82      * @return
83      */
84     public Object getValue(Connection conn,String sql, Object... params) {
85         Object count = null;
86         try {
87             // 调用queryRunner的query方法获取一个单一的值
88             count = queryRunner.query(conn, sql, new ScalarHandler<>(), params);
89         } catch (SQLException e) {
90             e.printStackTrace();
91         } 
92         return count;
93     }
94 }

  2、BookDAO

 1 public interface BookDao {
 2 
 3     /**
 4      * 从数据库中查询出所有的记录
 5      * 
 6      * @return
 7      */
 8     List<Book> getBooks(Connection conn);
 9 
10     /**
11      * 向数据库中插入一条记录
12      * 
13      * @param book
14      */
15     void saveBook(Connection conn,Book book);
16 
17     /**
18      * 从数据库中根据图书的id删除一条记录
19      * 
20      * @param bookId
21      */
22     void deleteBookById(Connection conn,String bookId);
23 
24     /**
25      * 根据图书的id从数据库中查询出一条记录
26      * 
27      * @param bookId
28      * @return
29      */
30     Book getBookById(Connection conn,String bookId);
31 
32     /**
33      * 根据图书的id从数据库中更新一条记录
34      * 
35      * @param book
36      */
37     void updateBook(Connection conn,Book book);
38 
39     /**
40      * 获取带分页的图书信息
41      * 
42      * @param page:是只包含了用户输入的pageNo属性的page对象
43      * @return 返回的Page对象是包含了所有属性的Page对象
44      */
45     Page<Book> getPageBooks(Connection conn,Page<Book> page);
46 
47     /**
48      * 获取带分页和价格范围的图书信息
49      * 
50      * @param page:是只包含了用户输入的pageNo属性的page对象
51      * @return 返回的Page对象是包含了所有属性的Page对象
52      */
53     Page<Book> getPageBooksByPrice(Connection conn,Page<Book> page, double minPrice, double maxPrice);
54 
55 }

  3、UserDAO

 1 public interface UserDao {
 2 
 3     /**
 4      * 根据User对象中的用户名和密码从数据库中获取一条记录
 5      * 
 6      * @param user
 7      * @return User 数据库中有记录 null 数据库中无此记录
 8      */
 9     User getUser(Connection conn,User user);
10 
11     /**
12      * 根据User对象中的用户名从数据库中获取一条记录
13      * 
14      * @param user
15      * @return true 数据库中有记录 false 数据库中无此记录
16      */
17     boolean checkUsername(Connection conn,User user);
18 
19     /**
20      * 向数据库中插入User对象
21      * 
22      * @param user
23      */
24     void saveUser(Connection conn,User user);
25 }

  4、BookDAOImpl

 1 public class BookDaoImpl extends BaseDao<Book> implements BookDao {
 2 
 3     @Override
 4     public List<Book> getBooks(Connection conn) {
 5         // 调用BaseDao中得到一个List的方法
 6         List<Book> beanList = null;
 7         // 写sql语句
 8         String sql = "select id,title,author,price,sales,stock,img_path imgPath from books";
 9         beanList = getBeanList(conn,sql);
10         return beanList;
11     }
12 
13     @Override
14     public void saveBook(Connection conn,Book book) {
15         // 写sql语句
16         String sql = "insert into books(title,author,price,sales,stock,img_path) values(?,?,?,?,?,?)";
17         // 调用BaseDao中通用的增删改的方法
18         update(conn,sql, book.getTitle(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(),book.getImgPath());
19     }
20 
21     @Override
22     public void deleteBookById(Connection conn,String bookId) {
23         // 写sql语句
24         String sql = "DELETE FROM books WHERE id = ?";
25         // 调用BaseDao中通用增删改的方法
26         update(conn,sql, bookId);
27             
28     }
29 
30     @Override
31     public Book getBookById(Connection conn,String bookId) {
32         // 调用BaseDao中获取一个对象的方法
33         Book book = null;
34         // 写sql语句
35         String sql = "select id,title,author,price,sales,stock,img_path imgPath from books where id = ?";
36         book = getBean(conn,sql, bookId);
37         return book;
38     }
39 
40     @Override
41     public void updateBook(Connection conn,Book book) {
42         // 写sql语句
43         String sql = "update books set title = ? , author = ? , price = ? , sales = ? , stock = ? where id = ?";
44         // 调用BaseDao中通用的增删改的方法
45         update(conn,sql, book.getTitle(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(), book.getId());
46     }
47 
48     @Override
49     public Page<Book> getPageBooks(Connection conn,Page<Book> page) {
50         // 获取数据库中图书的总记录数
51         String sql = "select count(*) from books";
52         // 调用BaseDao中获取一个单一值的方法
53         long totalRecord = (long) getValue(conn,sql);
54         // 将总记录数设置都page对象中
55         page.setTotalRecord((int) totalRecord);
56 
57         // 获取当前页中的记录存放的List
58         String sql2 = "select id,title,author,price,sales,stock,img_path imgPath from books limit ?,?";
59         // 调用BaseDao中获取一个集合的方法
60         List<Book> beanList = getBeanList(conn,sql2, (page.getPageNo() - 1) * Page.PAGE_SIZE, Page.PAGE_SIZE);
61         // 将这个List设置到page对象中
62         page.setList(beanList);
63         return page;
64     }
65 
66     @Override
67     public Page<Book> getPageBooksByPrice(Connection conn,Page<Book> page, double minPrice, double maxPrice) {
68         // 获取数据库中图书的总记录数
69         String sql = "select count(*) from books where price between ? and ?";
70         // 调用BaseDao中获取一个单一值的方法
71         long totalRecord = (long) getValue(conn,sql,minPrice,maxPrice);
72         // 将总记录数设置都page对象中
73         page.setTotalRecord((int) totalRecord);
74 
75         // 获取当前页中的记录存放的List
76         String sql2 = "select id,title,author,price,sales,stock,img_path imgPath from books where price between ? and ? limit ?,?";
77         // 调用BaseDao中获取一个集合的方法
78         List<Book> beanList = getBeanList(conn,sql2, minPrice , maxPrice , (page.getPageNo() - 1) * Page.PAGE_SIZE, Page.PAGE_SIZE);
79         // 将这个List设置到page对象中
80         page.setList(beanList);
81         
82         return page;
83     }
84 
85 }

  5、UserDAOImpl

 1 public class UserDaoImpl extends BaseDao<User> implements UserDao {
 2 
 3     @Override
 4     public User getUser(Connection conn,User user) {
 5         // 调用BaseDao中获取一个对象的方法
 6         User bean = null;
 7         // 写sql语句
 8         String sql = "select id,username,password,email from users where username = ? and password = ?";
 9         bean = getBean(conn,sql, user.getUsername(), user.getPassword());
10         return bean;
11     }
12 
13     @Override
14     public boolean checkUsername(Connection conn,User user) {
15         // 调用BaseDao中获取一个对象的方法
16         User bean = null;
17         // 写sql语句
18         String sql = "select id,username,password,email from users where username = ?";
19         bean = getBean(conn,sql, user.getUsername());
20         return bean != null;
21     }
22 
23     @Override
24     public void saveUser(Connection conn,User user) {
25         //写sql语句
26         String sql = "insert into users(username,password,email) values(?,?,?)";
27         //调用BaseDao中通用的增删改的方法
28         update(conn,sql, user.getUsername(),user.getPassword(),user.getEmail());
29     }
30 
31 }

  6、Book

 1 public class Book {
 2 
 3     private Integer id;
 4     private String title; // 书名
 5     private String author; // 作者
 6     private double price; // 价格
 7     private Integer sales; // 销量
 8     private Integer stock; // 库存
 9     private String imgPath = "static/img/default.jpg"; // 封面图片的路径
10     //构造器,get(),set(),toString()方法略
11 }

  7、User

1 public class User {
2 
3     private Integer id;
4     private String username;
5     private String password;
6     private String email;
7 }

  8、Page

 1 /**
 2  * 页码类
 3  *
 4  */
 5 public class Page<T> {
 6 
 7     private List<T> list; // 每页查到的记录存放的集合
 8     public static final int PAGE_SIZE = 4; // 每页显示的记录数
 9     private int pageNo; // 当前页
10 //    private int totalPageNo; // 总页数,通过计算得到
11     private int totalRecord; // 总记录数,通过查询数据库得到
12 }
原文地址:https://www.cnblogs.com/niujifei/p/15023496.html