Spring中使用Jdbcdaosupport、C3P0和properties
概念:
1、C3P0是一個開源的JDBC連接池,它實現了數據源和JNDI綁定,支持JDBC3規範和JDBC2的標準擴展。目前使用它的開源項目有Hibernate,Spring等。c3p0的出現,大大提高了應用程序和數據庫之間訪問效率。
2、C3P0是爲了對數據庫連接進行管理。原理是從pool裏獲取到的connection,是proxy包裝的connection,而對connection的釋放或者重用,是pool的管理責任:初始化池大小,維護池的大小(expand或shrink),管理unused、expired、checkout、checkin連接。真正底層的連接是jdbc自己的連接,而c3p0的管理部分,基本上使用的是synchronized關鍵字,使用timerTask定時器工作。
3、spring 提供用於操作JDBC工具類,類似:DBUtils。首先需要一個DAO類,寫該類屬性的get和set方法。然後按照DBUtils的思維,先創建數據源、配置DB的基本項(DriverClassName,URL,)、創建JDBC模板new JdbcTemplate(),然後通過API操作。——這個方法稍作了解,因爲這個思維並不Spring。當一個類中有了set方法,就應該想到DI(依賴反轉)。當一個類中出現了new,就應該想到IOC(控制反轉),讓Spring去做這些事。
4、配置時依賴連接池DataSource (數據源):創建數據源、創建模板(需要注入數據源)、配置DAO。搭建環境的時間比較長,因爲xml的配置基本一次配置完成,再也不用修改。——這個也稍微瞭解,當DAO繼承了JDBCDAOSUPPORT後,只需要注入數據源,底層會自動創建模板。
5、配置properties文件,將數據庫的基本信息寫在properties文件中,在xml文件中直接讀取properties文件信息,使得代碼的複用性更強。
下面就來實踐操作一下吧,在Spring中使用Jdbcdaosupport、C3P0和properties,如何完成與數據庫相關的操作。
步驟一 建表
create table LilyLearnSpring.t_user( id int primary key auto_increment, username varchar(50), password varchar(32) ); insert into t_user(username,password) values('dianer','1234'); insert into t_user(username,password) values('Lily','1213'); |
步驟二 導Jar包
1、C3P0連接池
com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
2、DBCP連接池
com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.commons.pool-1.5.3.jar
3、mysql驅動
mysql-connector-java-5.1.28-bin.jar
4、Spring JDBC開發
spring-jdbc-3.2.0.RELEASE.jar
5、事務
spring-tx-3.2.0.RELEASE.jar
6、Spring 4+1 常規
步驟三 編寫User類和DAO類
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}
}
public class UserDAO extends JdbcDaoSupport{
public void update(User user){
String sql="update t_user set username=?,password=? where id=?";
Object [] args={user.getUsername(),user.getPassword(),user.getId()};
this.getJdbcTemplate().update(sql, args);
}
public List<User> findAll(){
return this.getJdbcTemplate().query("select * from t_user", ParameterizedBeanPropertyRowMapper.newInstance(User.class));
}
public User getByName(String uname){
return this.getJdbcTemplate().queryForObject("select * from t_user where username = ?", ParameterizedBeanPropertyRowMapper.newInstance(User.class),uname);
}
}
步驟四 編寫properties文件
因爲myeclipse裏面沒有properties類型,所以new的時候先new 一個file類型,然後再輸入JdbcInfo.properties.
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/*******
jdbc.user=root
jdbc.password=*******
步驟五 配置xml配置文件
頭文件和AspectJ的一樣,直接複製過來的。
1、加載配置文件 context:property-placeholderlocation="classpath 儘量把這個classpath寫上,不然可能出亂七八糟的錯誤。
2、創建數據源,c3p0. 配置文件通過 ${key} 獲得內容
<bean id="?"class="com.mchange.v2.c3p0.ComboPooledDataSource">
3、配置DAO,只需要注入數據源,底層將自動創建模板
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:com/Lily/SpringLearning/I_c3p0/JdbcInfo.properties" />
<bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="userDAOId" class="com.Lily.SpringLearning.I_c3p0.UserDAO">
<property name="dataSource" ref="dataSourceId"></property>
</bean>
</beans>
步驟六 測試
public class TestC3p0 {
@Test
public void test() {
String xmlPath = "com/Lily/SpringLearning/I_c3p0/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserDAO userDao = (UserDAO) applicationContext.getBean("userDAOId");
User user = userDao.getByName("Lily");
System.out.println(user);
User u=new User();
u.setUsername("Lily");
u.setPassword("1213");
u.setId(2);
userDao.update(u);
List<User> list=userDao.findAll();
for(User s:list){
System.out.println(s);
}
}
}