Spring 之 JDBC 支持
Spring 框架针对数据库开发的应用提供了 JDBCTemplate 类,该类是 Spring 对 JDBC 支持的核心,提供了所有对数据库操作功能的支持
- DataSource
主要功能是获取数据库的连接,还可以引入数据库缓冲池和分布式事务的支持,可以作为访问数据库资源的标准接口
- SQLExceptionTranslator
该接口负责对 SQLException 进行转换,通过配置,可以使 JDBCTemplate 在需要处理 SQLException 时,完成一些转译工作
Spring 中 JDBC 的配置信息
在 Spring 配置文件中配置
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
| <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http:/www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id="dataSource" class="org.springframework.jdbc.dataSource.DriverManagerDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/spring" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.jdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="xxx" class="xxx"> <property name="jdbcTemplate" ref="jdbcTemplate" /> </bean> ... </beans>
|
在 Dao 层中注入 jdbcTemplate 实例, 该实例提供了大量的查询和更新数据库的方法,比如query()
,update()
等
Anything can go right will go right