本博客為原創:綜合 尚硅谷(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數據庫連接池
