[原创]java WEB学习笔记21:MVC案例完整实践(part 2)---DAO层设计

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 1.DAO层的设计和编写

  1) 加入C3P0数据源: 两个jar包 mchange-commons-java-0.2.3.4.jar,c3p0-0.9.2.1.jar ,数据库驱动jar包

    

  2)具体类设计及结构

   ①代码的结构

  

    ②代码

    I. 编写DAO(常用的 添删改查 的方法)

    DAO.java

  1 package com.jason.mvcapp.dao;
  2 
  3 import java.lang.reflect.ParameterizedType;
  4 import java.lang.reflect.Type;
  5 import java.sql.Connection;
  6 import java.util.List;
  7 
  8 import org.apache.commons.dbutils.QueryRunner;
  9 import org.apache.commons.dbutils.handlers.BeanHandler;
 10 import org.apache.commons.dbutils.handlers.BeanListHandler;
 11 import org.apache.commons.dbutils.handlers.ScalarHandler;
 12 
 13 import com.jsaon.mvcapp.db.JdbcUtils;
 14 import com.sun.org.apache.bcel.internal.generic.NEW;
 15 
 16 /**
 17  * 
 18  * @author: jason
 19  * @time:2016年5月25日下午2:59:06
 20  * @param <T>: 当前DAO 处理的实体的类型是什么
 21  * @description: 封装了CRUD 的方法 以供子类继承使用; 当前DAO直接在方法中获取数据库连接;整个DAO采取DBUtils解决方案;反射
 22  */
 23 public class DAO<T> {
 24         
 25     private QueryRunner queryRunner = new QueryRunner(); //线程安全 ,直接new
 26 
 27     private Class<T> clazz;
 28     
 29     public DAO() {
 30         //获取泛型父类的类型,getClass获取的是 子类的类型
 31         Type superClass = getClass().getGenericSuperclass();
 32         //
 33         if(superClass instanceof ParameterizedType){
 34             ParameterizedType parameterizedType = (ParameterizedType) superClass;
 35             //获取真正的泛型的参数,返回的是一个Type类型的数组
 36             Type[] typeArgs =parameterizedType.getActualTypeArguments();
 37             //判断数组不为空 且长度大于0
 38             if(typeArgs != null && typeArgs.length > 0){
 39                 //判断typeArgs[0]是否为Class 类型 ,即,泛型参数为一个类
 40                 if(typeArgs[0] instanceof Class){
 41                     clazz = (Class<T>) typeArgs[0]; //赋值给clazz对象
 42                 }
 43             }
 44         }
 45     }
 46 
 47     /**
 48      * @param sql
 49      * @param args
 50      * @description:返回某一个字段的值,例如:返回某一条记录的customerName
 51      */
 52     public <E> E getForValue(String sql, Object... args) {
 53         
 54         Connection connection = null;
 55         try {
 56             connection = JdbcUtils.getConnection();
 57             return (E) queryRunner.query(connection, sql, new ScalarHandler(), args);
 58             
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         } finally{
 62             JdbcUtils.releaseConnection(connection);
 63         }
 64         return null;
 65     }
 66 
 67     /**
 68      * @param sql
 69      * @param args
 70      * @return
 71      * @description:返回T 所对应的List
 72      */
 73     public List<T> getForList(String sql, Object... args) {
 74         Connection connection = null;
 75         try {
 76             connection = JdbcUtils.getConnection();
 77             
 78             return queryRunner.query(connection, sql, new BeanListHandler<T>(clazz), args);
 79             
 80         } catch (Exception e) {
 81             e.printStackTrace();
 82         } finally{
 83             JdbcUtils.releaseConnection(connection);
 84         }
 85 
 86         return null;
 87     }
 88 
 89     /**
 90      * @param sql
 91      *            :sql语句
 92      * @param args
 93      *            : sql语句的占位符
 94      * @return :返回对象
 95      * @description:返回对应的T 的一个实体类的对象
 96      */
 97     public T get(String sql, Object... args) {
 98         
 99         Connection connection = null;
100         try {
101             connection = JdbcUtils.getConnection();
102             return queryRunner.query(connection, sql, new BeanHandler<T>(clazz), args);    
103             
104         } catch (Exception e) {
105             e.printStackTrace();
106         } finally{
107             JdbcUtils.releaseConnection(connection);
108         }
109         
110         //System.out.println(clazz);
111     return null;
112     }
113 
114     /**
115      * @param sql
116      *            : sql语句
117      * @param ags
118      *            : sql语句的占位符
119      * @description:该方法封装了 INSERT ,DELETE,UPDATE 操作
120      */
121     public void update(String sql, Object... ags){
122         
123         Connection connection = null;
124         try {
125             connection = JdbcUtils.getConnection();    
126             queryRunner.update(connection, sql, ags);
127             
128         } catch (Exception e) {
129             e.printStackTrace();
130         } finally{
131             JdbcUtils.releaseConnection(connection);
132         }
133     }
134 
135 }

  

    CustomerDAO.java

 1 package com.jason.mvcapp.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.jsaon.mvcapp.domain.Customer;
 6 
 7 
 8 /**
 9  * @author: jason
10  * @time:2016年5月25日下午3:28:00
11  * @description:
12  */
13 
14 public interface CustomerDAO {
15 
16     //查询所有
17     public List<Customer> getAll();
18     
19     //保存操作
20     public void save(Customer coustomer);
21     
22     //更新前,先查询
23     public Customer get(Integer id);
24     
25     //删除用户
26     public void delete(Integer id);
27     
28     //查看与参数相同的名字有多少个记录数
29     public long getCountWithName(String name);
30     
31 }

 

 II.JdbcUtils工具类  

  JdbcUtils.java

 1 package com.jsaon.mvcapp.db;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 
 6 import javax.sql.DataSource;
 7 
 8 import com.mchange.v2.c3p0.ComboPooledDataSource;
 9 
10 /**
11  * @author: jason
12  * @time:2016年5月25日下午3:23:46
13  * @description:使用c3p0数据库连接池,完成工具类
14  */
15 
16 public class JdbcUtils {
17 
18     /**
19      * @param connection
20      * @description:释放Connection连接
21      */
22     public static void releaseConnection(Connection connection) {
23         
24         try {
25             if(connection != null){
26                 connection.close();
27             }
28             
29         } catch (Exception e) {
30             e.printStackTrace();
31         }
32     }
33     
34     
35     
36     
37     //强调:数据源只有一份就好了,初始化 放在静态代码块中
38     private static DataSource  dataSource = null;
39     
40     static{
41         dataSource = new ComboPooledDataSource("mvcapp"); //读取mvcapp的配置,也就是c3p0-config.xml的配置信息
42         
43     }
44     /**
45      * @return
46      * @throws SQLException 
47      * @description: 获取数据库连接池连接
48      */
49     public static Connection getConnection() throws SQLException {
50         return dataSource.getConnection();
51     }
52 
53     
54     
55 }

   

   c3p0-config.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <c3p0-config>
 3   <!-- This app is massive! -->
 4   <named-config name="mvcapp"> 
 5   
 6       <!-- 连接数据库的节本信息 -->
 7       <property name="user">登录数据库的用户名</property>
 8       <property name="password">密码</property>
 9       <property name="driverClass">驱动类</property>
10       <property name="jdbcUrl">url</property>
11       
12       
13       
14       <!-- 连接池的配置信息 -->
15     <property name="acquireIncrement">5</property>
16     <property name="initialPoolSize">10</property>
17     <property name="minPoolSize">10</property>
18     <property name="maxPoolSize">50</property>
19     <property name="maxStatements">20</property> 
20     <property name="maxStatementsPerConnection">5</property>
21   </named-config>
22 </c3p0-config>

  III.提供CustomerDAO 接口的实现类 CustometDAOImpl

 1 package com.jason.mvcapp.dao.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.jason.mvcapp.dao.CustomerDAO;
 6 import com.jason.mvcapp.dao.DAO;
 7 import com.jsaon.mvcapp.domain.Customer;
 8 
 9 /**
10  * @author: jason
11  * @time:2016年5月25日下午3:45:06
12  * @description:对CustomerDAO 的实现
13  */
14 public class CustomerDAOJdbcImpl extends DAO<Customer> implements CustomerDAO {
15 
16     @Override
17     public List<Customer> getAll() {
18         String sql = "SELECT * FROM customers";
19         return getForList(sql);
20     }
21 
22     @Override
23     public void save(Customer customer) {
24         String sql = "INSERT INTO customers(name, address, phone) VALUES(?,?,? )";
25         update(sql,customer.getName(),customer.getAddress(),customer.getPhone());
26     }
27 
28 
29     @Override
30     public Customer get(Integer id) {
31         String sql = "SELECT id, name, address, phone FROM customers WHERE id = ?";
32         return get(sql,id);
33         
34     }
35 
36     @Override
37     public void delete(Integer id) {
38         String sql = "DELETE FROM customers WHERE id = ?";
39         update(sql, id);
40     }
41 
42     @Override
43     public long getCountWithName(String name) {
44         String sql = "SELECT count(id) FROM customers WHERE name = ?";
45         return getForValue(sql, name);
46     }
47 
48 }

  IV 测试代码(通过创建相应的junit测试类,测试各个类的方法)

 CustomerDAOJdbcImplTest.java

 1 package com.jason.mvcapp.test;
 2 
 3 import static org.junit.Assert.fail;
 4 
 5 import java.util.List;
 6 
 7 import org.junit.Test;
 8 
 9 import com.jason.mvcapp.dao.CustomerDAO;
10 import com.jason.mvcapp.dao.impl.CustomerDAOJdbcImpl;
11 import com.jsaon.mvcapp.domain.Customer;
12 
13 public class CustomerDAOJdbcImplTest {
14 
15     private CustomerDAO customerDAO =new CustomerDAOJdbcImpl();
16     @Test
17     public void testGetAll() {
18         List<Customer> customers = customerDAO.getAll();
19         System.out.println(customers);
20      }
21 
22     @Test
23     public void testSaveCustomer() {
24         Customer customer = new Customer();
25         customer.setAddress("铁岭");
26         customer.setName("黑土");
27         customer.setPhone("15101035648");
28         customerDAO.save(customer);
29     }
30  
31     @Test
32     public void testGetInteger() {
33         Customer customer = customerDAO.get(1);
34         System.out.println(customer);
35     }
36 
37     @Test
38     public void testDelete() {
39         customerDAO.delete(1);
40     }
41 
42     @Test
43     public void testGetCountWithName() {
44         long count =    customerDAO.getCountWithName("白云");
45         System.out.println(count);
46     }
47 
48 }

  JdbcUtilsTest.java

 1 package com.jason.mvcapp.test;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 
 6 import org.junit.Test;
 7 
 8 import com.jsaon.mvcapp.db.JdbcUtils;
 9 
10 
11 
12 public class JdbcUtilsTest {
13 
14     @Test
15     public void testGetConnection() throws SQLException {
16         
17         Connection connection = JdbcUtils.getConnection();
18         System.out.println(connection);
19     }
20 
21 }

2.总结

  1)从代码层面,理解MVC设计模式

  2)使用dbUtils工具类,操作jdbc

  3)配置,使用c3p0数据库连接池

回看  案例完整实践(part 1)---MVC架构分析

原文地址:https://www.cnblogs.com/jasonHome/p/5528269.html