Spring框架在数据库开发中的应用主要使用的是JdbcTemplate类,是Spring JDBC的核心类,提供了对所有数据库操作功能的支持。继承了抽象类JdbcAccessor,同时实现了接口JdbcOperations。
JdbcAccessor为子类提供了一些访问数据库时的公共属性,具体如下:
- DataSource:器主要功能是获取数据库连接,具体实现时还可以引入对数据库连接的缓冲池和分布式事务的支持,可以作为访问数据库资源的标准接口。
- SQLExceptionTranslator:该接口负责对SQLException进行转译。通过必要的设置或者获取SQLExceptionTranslator中的方法,可以使JdbcTemplate在需要处理SQLException时,委托SQLExceptionTranslator的实现类来完成相关的转译工作。
Spring JDBC模块主要由4个包组成:
- core:核心包。包含JDBC的核心功能,包括JdbcTemplate类、SimpleJdbcInsert类、SimpleJdbcCall类以及NameParameterJdbcTemplate类。
- dataSource:数据源包。访问数据源的使用工具,它有多种数据源的实现,可以在JavaEE容器外部测试JDBC代码。
- object:对象包。以面向对象的方式访问数据库,它允许执行查询并返回结果作为业务对象,可以在数据表的列和业务对象的属性之间映射查询结果。
- support:支持包。包含core和object包的支持类。例如:提供异常转换功能的SQLException类。
使用到的jar包:spring-jdbc-5.0.4.RELEASE.jar【Spring包中已提供】
1、applicationContext.xml配置的代码:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<!--1、配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--数据库驱动名称,不同类型数据库的名称-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!--连接数据库的数据源所在的url地址-->
<property name="url" value="jdbc:mysql://localhost:3306/springdemo"/>
<!--连接数据库的用户名-->
<property name="username" value="root"/>
<!--连接数据库的密码-->
<property name="password" value="123456"/>
</bean>
<!--2、配置JDBC模板-->
<!--
定义JdbcTemplate时,需要将dataSource注入到JdbcTemplate中,
而其他需要使用JdbcTemplate的Bean,也需要将JdbcTemplate注入到该Bean中
(通常注入到数据访问层Dao类中,在Dao类中进行与数据库的相关操作)
-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--默认必须使用数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--3、配置注入的实体类,以下为模拟代码-->
<bean id="xxx" class="com.xxx.Xxx">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>