spring整合JDBC

spring整合JDBC

spring中提供了一个可以操作数据库的对象,对象封装了jdbc技术。这个对象的名字就叫JDBCTemplate,JDBC模板对象。这个对象和DBUtils中的QueryRunner对象非常相似。

准备工作

  • 导包
    • 4+2(4个核心包+2个日志包)
    • spring-test、spring-aop(新版本需要)、junit4类库
    • c3p0连接池、JDBC驱动包
    • spring-jdbc、spring-tx(需要spring事务包的支持)
  • 准备数据库测试
  • 解决数据库中文乱码
    (jdbc:mysql:///springmvc?characterEncoding=utf-8)

spring整合JDBC中application.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	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.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd ">

	<!--1将连接池交给spring容器管理  -->
	<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql:///springmvc?characterEncoding=utf-8"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123"></property>
	</bean>
	
	<!--2将JDBCTemplate放入spring容器  -->
	<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!--3将UserDao放入spring容器  -->
	<bean name="userDao" class="com.fei.a_jdbctemplate.UserDaoImpl">
		<property name="jt" ref="jdbcTemplate"></property>
	</bean>
	
</beans> 

获得userDao对象的代码

// 1创建容器对象
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	// 2向容器要对象
	UserDao userDao = (UserDao) ac.getBean("userDao");

spring读取外部数据库连接配置文件(db.properties)

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///springmvc?characterEncoding=utf-8
jdbc.user=root
jdbc.password=123
<!-- 告诉spring让他去读取db.properties配置文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!--1将连接池交给spring容器管理  -->
	<bean name="dataSource" 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>
posted on 2019-07-16 22:26  行之间  阅读(154)  评论(0编辑  收藏  举报