Spring中使用Jdbcdaosupport、C3P0和properties

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);			
		}
		
		
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章