對一個簡單的數據庫應用,由于對數據庫的訪問不是很頻繁,這時可以簡單地在需要訪問數據庫時,就新創建一個連接,就完后就關閉它,這樣做也不會帶來什么性能上的開銷。但是對于一個復雜的數據庫應用,情況就完全不同而,頻繁的建立、關閉連接,會極大地減低系統的性能,因為對于連接的使用成了系統性能的瓶頸。
通過建立一個數據庫連接池以及一套連接使用管理策略,可以達到連接復用的效果,使得一個數據庫連接可以得到安全、高效的復用,避免了數據庫連接頻繁建立、關閉的開銷。
數據庫連接池的基本原理是在內部對象池中維護一定數量的數據庫連接,并對外暴露數據庫連接獲取和返回方法。如:外部使用者可通過getConnection方法獲取連接,使用完畢后再通過releaseConnection方法將連接返回,注意此時連接并沒有關閉,而是由連接池管理器回收,并為下一次使用做好準備。
數據庫連接池技術帶來的好處:
1、資源重用
由于數據庫連接得到重用,避免了頻繁創建、釋放鏈接引起的大量性能開銷。在減少系統消耗的基礎上,另一方面也增進了系統運行環境的平穩性(減少內存碎片以及數據庫臨時進行/線程數量)
2、更快地系統響應速度
數據庫連接池在初始化過程中,往往已經創建了若干數據庫連接池置于池中備用。此時連接的初始化工作均已完成,對于業務請求處理而言,直接利用現有可用連接,避免了數據庫連接初始化和釋放過程的時間開銷,從而縮減了系統整體響應時間
3、統一的連接管理,避免數據庫連接泄露
在較為完備的數據庫連接池實現中,可根據預先的連接占用超時設定,強制收回被占用連接,從而避免了常規數據庫連接操作中可能出現的資源泄露。
目前數據庫連接池產品是非常多的,主要有:
1、dbcp
dbcp,即DataBase Connection PoolApache出品,Spring開發組推薦使用的數據庫連接池,開發較為活躍,是一個使用極為廣泛的數據庫連接池產品。不過從網上
2、c3p0
Hibernate開發組推薦使用的數據庫連接池,它實現了數據源和JNDI的綁定
3、Proxool
Proxool的口碑較好,沒什么負面評價(比如dbcp就是因為Hibernate認為它BUG太多Hibernate才不推薦使用的),也是Hibernate開發組推薦使用的數據庫連接池,不過使用者不算多,開發不夠活躍。這個連接池提供了連接池監控的功能,方便易用,便于發現連接池泄露的情況
基于Spring的JDBC基本框架搭建
先講一下使用Spring實現JDBC,數據庫連接池就用Spring開發組推薦的DBCP,DBCP需要三個jar包,先下載一下:
1、commons-dbcp-1.4.jar,官方網站上有,點我下載
2、commons.pool-1.6.jar,官方網站上有,點我下載
3、commons.collections4-4.0.jar,官方網站上有
下載了這三個jar包之后請導入自己的工程中(注意MySql的包別忘記導入了),雖然dbcp和pool都出了dbcp2和pool2的版本,Apache官網上都可以下載,但是這里提供的還是dbcp1和pool1的版本下載地址,一個原因是dbcp2和pool2都只可以在JDK1.7及JDK1.7以上的版本運行,而dbcp1和pool1則可以在JDK1.6的版本運行,考慮到MyEclipse10默認自帶的JRE就是1.6版本的,所以這里下載、使用dbcp1和pool1。想要dbcp2和pool2的可以自己去Apache官網下載,不過要注意,dbcp2必須和pool2一組,dbcp1必須和pool1一組,不可以混著用。
JDBC,我之前寫過一篇文章,數據庫建立和實體類都是用的原文章里面的,這里只是把原生的JDBC搬到Spring JDBC下而已,看下最基礎的寫法,再添加功能,學生管理類為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class StudentManager { private JdbcTemplate jdbcTemplate; private static StudentManager instance = new StudentManager(); public static StudentManager getInstance() { return instance; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this .jdbcTemplate = jdbcTemplate; } } |
Spring的XML配置文件命名為jdbc.xml,jdbc.xml的寫法為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> < bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" > <!-- 驅動包名 --> < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> <!-- 數據庫地址 --> < property name = "url" value = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8;" /> <!-- 用戶名 --> < property name = "username" value = "root" /> <!-- 密碼 --> < property name = "password" value = "root" /> <!-- 最大連接數量 --> < property name = "maxActive" value = "150" /> <!-- 最小空閑連接 --> < property name = "minIdle" value = "5" /> <!-- 最大空閑連接 --> < property name = "maxIdle" value = "20" /> <!-- 初始化連接數量 --> < property name = "initialSize" value = "30" /> <!-- 連接被泄露時是否打印 --> < property name = "logAbandoned" value = "true" /> <!-- 是否自動回收超時連接 --> < property name = "removeAbandoned" value = "true" /> <!-- 超時等待時間(以秒為單位) --> < property name = "removeAbandonedTimeout" value = "10" /> </ bean > < bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" > < property name = "dataSource" ref = "dataSource" /> </ bean > < bean id = "studentManager" class = "com.xrq.jdbc.StudentManager" factory-method = "getInstance" > < property name = "jdbcTemplate" ref = "jdbcTemplate" /> </ bean > </ beans > |
主函數為:
1
2
3
4
5
6
7
|
public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "jdbc.xml" ); System.out.println(StudentManager.getInstance()); System.out.println(StudentManager.getInstance().getJdbcTemplate()); } |
運行沒什么問題,得到StudentManager的引用地址和StudentManager中屬性jdbcTemplate的引用地址,說明整個連接、注入都沒問題。
JDBCTemple是Spring里面最基本的JDBC模板,利用JDBC和簡單的索引參數查詢提供對數據庫的簡單訪問。除了JDBCTemplate,Spring還提供了NamedParameterJdbcTemplate和SimpleJdbcTemplate兩個類,前者能夠在執行查詢時把值綁定到SQL里的命名參數而不是使用索引,后者利用Java 5的特性比如自動裝箱、泛型和可變參數列表來簡化JDBC模板的使用。具體使用哪個看個人喜好,這里使用JdbcTemplate,所以把JdbcTemplate添加到學生管理類中。
另外:
1、dbcp提供很多參數給用戶配置,每個參數的意思都以注釋的形式寫在.xml里面了,更加具體要知道每個參數的意思可以上網查詢一下
2、注意dbcp的屬性url,url指的是數據庫連接地址,遇到特殊字符需要轉義,所以這里的"&"變成了"&",不然會報錯
基于Spring的JDBC增刪改查
上面一部分搭建了一個Spring JDBC的基礎框架,下面看一下Java代碼如何實現CRUD,這個過程中jdbc.xml都不需要變化。
1、添加一個學生信息,代碼為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 添加學生信息 public boolean addStudent(Student student) { try { jdbcTemplate.update( "insert into student values(null,?,?,?)" , new Object[]{student.getStudentName(), student.getStudentAge(), student.getStudentPhone()}, new int []{Types.VARCHAR, Types.INTEGER, Types.VARCHAR}); return true ; } catch (Exception e) { return false ; } } |
2、根據Id刪除指定學生信息,代碼為:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// 根據Id刪除單個學生信息 public boolean deleteStudent( int id) { try { jdbcTemplate.update( "delete from student where studentId = ?" , new Object[]{id}, new int []{Types.INTEGER}); return true ; } catch (Exception e) { return false ; } } |
3、根據Id更新學生信息,代碼為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 根據Id更新指定學生信息 public boolean updateStudent( int Id, Student student) { try { jdbcTemplate.update( "update student set studentName = ?, studentAge = ?, studentPhone = ? where studentId = ?" , new Object[]{student.getStudentName(), student.getStudentAge(), student.getStudentPhone(), Id}, new int []{Types.VARCHAR, Types.INTEGER, Types.VARCHAR, Types.INTEGER}); return true ; } catch (Exception e) { return false ; } } |
4、根據Id查詢學生信息,代碼為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 根據學生Id查詢單個學生信息 public Student getStudent( int id) { try { return (Student)jdbcTemplate.queryForObject( "select * from student where studentId = ?" , new Object[]{id}, new int []{Types.INTEGER}, new RowMapper<Student>(){ public Student mapRow(ResultSet rs, int arg1) throws SQLException { Student student = new Student(rs.getInt( 1 ), rs.getString( 2 ), rs.getInt( 3 ), rs.getString( 4 )); return student; } }); } // 根據Id查詢學生信息拋異常, 不管什么原因, 認為查詢不到該學生信息, 返回null catch (DataAccessException e) { return null ; } } |
5、查詢所有學生信息,代碼為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// 查詢所有學生信息 public List<Student> getStudents() { List<Map<String, Object>> resultList = jdbcTemplate.queryForList( "select * from student" ); List<Student> studentList = null ; if (resultList != null && !resultList.isEmpty()) { studentList = new ArrayList<Student>(); Map<String, Object> map = null ; for ( int i = 0 ; i < resultList.size(); i++) { map = resultList.get(i); Student student = new Student( (Integer)map.get( "studentId" ), (String)map.get( "studentName" ), (Integer)map.get( "studentAge" ), (String)map.get( "studentPhone" ) ); studentList.add(student); } } return studentList; } |
這就是簡單的CRUD操作,有了這5個作為基礎,其余都可以在這5個的基礎上做擴展,就不繼續詳細寫下去了,說幾個注意點:
1、個人使用經驗來說,除了最后一個查詢所有的以外,建議給其他的都加上try...catch...塊,因為在操作失敗的時候會拋出異常,捕獲了就可以知道這次的操作失敗了,否則只能程序終止,而自己也不知道操作到底是成功還是失敗
2、添加信息、更新信息不建議把每個待操作的字段都作為形參而建議形參就是一個Student實體類,這樣一來更符合面向對象的設計原則,二來形參列表的字段多很容易導致出錯
3、update、query方法,如果有占位符?的話,建議選擇有參數類型的重載方法,指定每個占位符的字段類型,就像我上面代碼寫的那樣
最后,這里講的都是jdbcTemplate的基本使用,jdbcTemplate里面還有很多方法,就不一一細說了,可以自己去試一下,也可以查閱Spring API文檔。
讀取配置文件中的數據
之前我們都是把數據庫連接的一些屬性配置在db.properties里面的,這樣方便修改,而這里卻是在jdbc.xml里面寫死的,所以要想一個辦法怎么可以從db.properties里面讀取出配置,context幫助開發者實現了這一點,看一下jdbc.xml如何寫:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> < context:property-placeholder location = "classpath:db.properties" /> < bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" > <!-- 驅動包名 --> < property name = "driverClassName" value = "${mysqlpackage}" /> <!-- 數據庫地址 --> < property name = "url" value = "${mysqlurl}" /> <!-- 用戶名 --> < property name = "username" value = "${mysqlname}" /> <!-- 密碼 --> < property name = "password" value = "${mysqlpassword}" /> <!-- 最大連接數量 --> < property name = "maxActive" value = "150" /> <!-- 最小空閑連接 --> < property name = "minIdle" value = "5" /> <!-- 最大空閑連接 --> < property name = "maxIdle" value = "20" /> <!-- 初始化連接數量 --> < property name = "initialSize" value = "30" /> <!-- 連接被泄露時是否打印 --> < property name = "logAbandoned" value = "true" /> <!-- 是否自動回收超時連接 --> < property name = "removeAbandoned" value = "true" /> <!-- 超時等待時間(以秒為單位) --> < property name = "removeAbandonedTimeout" value = "10" /> </ bean > < bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" > < property name = "dataSource" ref = "dataSource" /> </ bean > < bean id = "studentManager" class = "com.xrq.jdbc.StudentManager" factory-method = "getInstance" > < property name = "jdbcTemplate" ref = "jdbcTemplate" /> </ bean > </ beans > |
重點就是第10行,第14、第16、第18、第20行就是取屬性的寫法,和前端的FTL語言類似。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/xrq730/p/4922136.html