Spring(2)之 (2.3 Spring JDBC Template的使用)

Spring 对 JDBC的支持:

Spring 对于JDBC的支持体现在:

  1. 连接池
  2. JDBCTemplate工具类,简化了JDBC开发

使用 Spring JDBC步骤:

  1. 导包
    spring-jdbc-4.0.6.RELEASE
    spring-tx-4.0.6.RELEASE
    c3p0-0.9.1.2
    mysql-connector-java-5.1.12-bin
    (【bean.xml】中:① 创建数据库连接池对象 dataSource② 创建 jdbcTemplate 的 bean对象(因为JdbcTemplate类中有 dataSource属性,所以创建时用 ref引入 dataSource)、③ 创建类 userDao 的 bean对象(如userDao对象)时,对象中有 jdbcTemplate属性,所以创建时用 ref引入jdbcTemplate;【UserDao.java】:将 jdbcTemplate作为类属性,利用 set方法将其注入进来,然后直接调用 jdbcTemplate自带的方法执行sql语句。)
    bean.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 创建连接池对象 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
    	<property name="user" value="root"></property>
    	<property name="password" value="12345"></property>
    </bean>
    <!-- JdbcTemplate工具类 -->
    <!-- 创建jdbcTemplate对象(将dataSource注入) -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
     <!-- 创建UserDao对象(将jdbcTemplate注入) -->
    <bean id="userDao" class="com.asd.spring.UserDao">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
    
</beans>

UserDao.java

public class UserDao{
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
		this.jdbcTemplate=jdbcTemplate;
	}
	public void save() throws Exception{ //添加方法
		String sql="insert into user(username,age) values('Test',1)";
		jdbcTemplate.update(sql);
	}
	public void queryAll() throws Exception{ //查询全部方法
		String sql="select id,username,age from user";
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
		System.out.println(list);
		return null;
	}
	public List<User> query() throws Exception{ //查询方法
		String sql="select id,username,age from user";
		//行处理
		return jdbcTemplate.query(sql,new RowMapper<User>(){
			public User mapRow(ResultSet rs,int index)throws SQLException{
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setAge(rs.getInt("age"));
				return user;
			}
		});	
	}
}

 
eg 1. Spring 对 JDBC的支持(未改前):
(Spring对JDBC的支持优化:1.连接管理;2.重复代码的优化。 UserDao.java中:使用数据库连接池作为属性,数据库连接池是用IOC容器生成,所以生成 DataSource的 bean对象 dataSource后,再在< property>标签中用 ref属性注入到 userDao的 bean对象中;dataSource再通过 set方法注入进来;
save()方法中通过 dataSource创建连接,通过连接创建Statement,再执行 sql语句,关闭 statement、conn;由于创建连接、创建Statement对象、执行、关闭等语句要重复,过于麻烦,可以使用 jdbcTemplate来进行 JDBC操作优化(不需要创建conn、创建Statement、.execute(sql)执行、关闭conn、statemnt,只需要一个 dataSource、一个sql语句,创建 jdbcTemplate时利用其构造方法将 dataSource注入,再调用其自带的 update(sql)方法执行 sql语句即可); bean.xml中:创建连接池对象 、创建UserDao对象(将dataSource属性注入);)

1.1 User.java

public class User{
	private int id;
	private String username;
	private int age;
	set、get()、toString();
}

1.2 UserDao.java_1(使用jdbcTemplate对JDBC操作优化后且将 jdbcTemplate作为类属性)
(接下面,将 jdbcTemplate作为类属性,此时 数据库连接池dataSource属性类以及其 set方法不需要了,需要一个 jdbcTemplate的 set方法将其注入;此时 bean.xml中创建 UserDao的 bean对象时,在UserDao的< property>标签中用 ref属性注入的是 jdbcTemplate对象而非 dataSource对象了(先创建 jdbcTemplate的 bean对象),jdbcTemplate的 bean对象用 ref属性注入的是 dataSource对象;)

public class UserDao{
	//使用连接池,用IOC容器注入
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
		this.jdbcTemplate=jdbcTemplate;
	}
	public void save() throws Exception{ //添加方法
		String sql="insert into user(username,age) values('Test',1)";
		jdbcTemplate.update(sql);
	}
	public void queryAll() throws Exception{ //查询全部方法
		String sql="select id,username,age from user";
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
		System.out.println(list);
		return null;
	}
	public List<User> query() throws Exception{ //查询方法
		String sql="select id,username,age from user";
		//行处理
		return jdbcTemplate.query(sql,new RowMapper<User>(){
			public User mapRow(ResultSet rs,int index)throws SQLException{
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setAge(rs.getInt("age"));
				return user;
			}
		});	
	}
}

1.2 UserDao.java_2(使用jdbcTemplate对JDBC操作优化后未将 jdbcTemplate作为类属性)
(只需要一个 jdbcTemplate(创建时将 dataSource注入)来执行 sql语句:添加方法中调用 jdbcTemplate自带的 update(sql)来执行 sql语句;查询全部方法中调用 jdbcTemplate自带的 queryForList(sql)来执行 sql语句,返回的是一个 Map类型的 list集合;对行处理调用query(sql,new RowMapper(){ }); 由于 new JdbcTemplate(dataSource)在每个方法中都重复,所以可以将 jdbcTemplate作为类属性单独提取出来,到上面;)

public class UserDao{
	//使用连接池,用IOC容器注入
	private DataSource dataSource;
	public void setDataSource(DataSource dataSource){
		this.dataSource=dataSource;
	}
	public void save() throws Exception{ //添加方法
		String sql="insert into user(username,age) values('Test',1)";
		//使用jdbcTemplate对JDBC操作优化
		JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql);
	}
	public void queryAll() throws Exception{ //查询全部方法
		String sql="select id,username,age from user";
		JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
		System.out.println(list);
		return null;
	}
	public List<User> query() throws Exception{ //查询方法
		String sql="select id,username,age from user";
		JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
		//行处理
		return jdbcTemplate.query(sql,new RowMapper<User>(){
			public User mapRow(ResultSet rs,int index)throws SQLException{
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setAge(rs.getInt("age"));
				return user;
			}
		});	
	}
}

1.2 UserDao.java_3(未使用jdbcTemplate时:)
(需要通过 dataSource创建 conn,通过 conn得到 statement,再通过 statement执行 sql语句,在关闭statement、conn;到上面;)

public class UserDao{
	//使用连接池,用IOC容器注入
	private DataSource dataSource;
	public void setDataSource(DataSource dataSource){
		this.dataSource=dataSource;
	}
	public void save() throws Exception{
		//JDBC连接
		Connection conn=dataSource.getConnection();
		//Statement
		Statement statement=conn.createStatement();
		String sql="insert into User(username,age) values('Test',1);
		statement.execute(sql);
		statement.close();
		conn.close();
	}
}

1.3 bean.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 创建连接池对象 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
    	<property name="user" value="root"></property>
    	<property name="password" value="12345"></property>
    </bean>
    <!-- JdbcTemplate工具类 -->
    <!-- 创建jdbcTemplate对象(将dataSource注入) -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
     <!-- 创建UserDao对象(将jdbcTemplate注入) -->
    <bean id="userDao" class="com.asd.spring.UserDao">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
    
     <!-- 创建UserDao对象(将dataSource注入) -->
    <!--<bean id="userDao" class="com.asd.spring.UserDao">
    	<property name="dataSource" ref="dataSource"></property>
    </bean> -->
</beans>

Test.java

public class Test{
	ApplicationContext applicationContext=ClassPathXmlApplicationContext("bean.xml");
	public void testApp{
		UserDao userDao=(UserDao)applicationContext.getBean("userDao");
		try{
			// userDao.save();
			// userDao.queryAll();
			System.out.println(userDao.query());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

运行结果:(测试方法中调用 userDao中的查询全部的方法queryAll)
在这里插入图片描述
运行结果:(测试方法中调用 userDao中的 query方法)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41029923/article/details/84291336
今日推荐