Spring-JdbcTemplate
- 它是 spring框架中提供的一个对象,是对原始 Jdbc API对象的简单封装。
1.需要的jar包:
在maven中导入jar
包坐标如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2.Spring简单配置Template:
- 使用Spring内置的数据源
DriverManagerDataSource
。
<?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">
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case01"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
- 测试:
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
jt.execute("insert into account(name,money)values('ATFWUS',888)");
//增
jt.update("insert into account(name,money)values(?,?)","ATFWUSS",8888);
//改
jt.update("update account set name=?,money=? where id=?","AT",8888,10);
//删
jt.update("delete from account where id=?",18);
//查
List<Account> accounts = jt.query("select * from account where money > ?",
new BeanPropertyRowMapper<Account>(Account.class),8888);
Long count = jt.queryForObject("select count(*) from account where money > ?"
,Long.class,88);
3.JdbcDaoSupport :
- 在dao层若使用Spring配置的话,需要注入JdbcTemplate,如果我们使用让dao层的类继承
JdbcDaoSupport
,就可以把这些交给Spring处理,但是,一旦继承此类,将无法再使用注解的方式去配置。 JdbcDaoSupport
源码:
/**
* Convenient super class for JDBC-based data access objects.
*
* <p>Requires a {@link javax.sql.DataSource} to be set, providing a
* {@link org.springframework.jdbc.core.JdbcTemplate} based on it to
* subclasses through the {@link #getJdbcTemplate()} method.
*
* <p>This base class is mainly intended for JdbcTemplate usage but can
* also be used when working with a Connection directly or when using
* {@code org.springframework.jdbc.object} operation objects.
*
* @author Juergen Hoeller
* @since 28.07.2003
* @see #setDataSource
* @see #getJdbcTemplate
* @see org.springframework.jdbc.core.JdbcTemplate
*/
public abstract class JdbcDaoSupport extends DaoSupport {
@Nullable
private JdbcTemplate jdbcTemplate;
/**
* Set the JDBC DataSource to be used by this DAO.
*/
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
/**
* Create a JdbcTemplate for the given DataSource.
* Only invoked if populating the DAO with a DataSource reference!
* <p>Can be overridden in subclasses to provide a JdbcTemplate instance
* with different configuration, or a custom JdbcTemplate subclass.
* @param dataSource the JDBC DataSource to create a JdbcTemplate for
* @return the new JdbcTemplate instance
* @see #setDataSource
*/
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
/**
* Return the JDBC DataSource used by this DAO.
*/
@Nullable
public final DataSource getDataSource() {
return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null);
}
/**
* Set the JdbcTemplate for this DAO explicitly,
* as an alternative to specifying a DataSource.
*/
public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
/**
* Return the JdbcTemplate for this DAO,
* pre-initialized with the DataSource or set explicitly.
*/
@Nullable
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
/**
* Initialize the template-based configuration of this DAO.
* Called after a new JdbcTemplate has been set, either directly
* or through a DataSource.
* <p>This implementation is empty. Subclasses may override this
* to configure further objects based on the JdbcTemplate.
* @see #getJdbcTemplate()
*/
protected void initTemplateConfig() {
}
@Override
protected void checkDaoConfig() {
if (this.jdbcTemplate == null) {
throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");
}
}
/**
* Return the SQLExceptionTranslator of this DAO's JdbcTemplate,
* for translating SQLExceptions in custom JDBC access code.
* @see org.springframework.jdbc.core.JdbcTemplate#getExceptionTranslator()
*/
protected final SQLExceptionTranslator getExceptionTranslator() {
JdbcTemplate jdbcTemplate = getJdbcTemplate();
Assert.state(jdbcTemplate != null, "No JdbcTemplate set");
return jdbcTemplate.getExceptionTranslator();
}
/**
* Get a JDBC Connection, either from the current transaction or a new one.
* @return the JDBC Connection
* @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
* @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
*/
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
DataSource dataSource = getDataSource();
Assert.state(dataSource != null, "No DataSource set");
return DataSourceUtils.getConnection(dataSource);
}
/**
* Close the given JDBC Connection, created via this DAO's DataSource,
* if it isn't bound to the thread.
* @param con Connection to close
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
*/
protected final void releaseConnection(Connection con) {
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
- dao层测试类:
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?"
,new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?"
,new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?"
,account.getName(),account.getMoney(),account.getId());
}
}
Spring - 事务控制
- Spring中提供类一组用于事务控制的API。
1.API介绍:
-
PlatformTransactionManager
:此接口是 spring的事务管理器,它里面提供了我们常用的操作事务的方法。-
TransactionStatus getTransaction(TransactionDefinition definition)
:获取事务状态信息。 -
void commit(TransactionStatus status)
:提交事务。 -
void rollback(TransactionStatus status)
:回滚事务。 -
实现类:
-
DataSourceTransactionManager
:使用 Spring JDBC或 iBatis 进行持久化数据时使用。 -
HibernateTransactionManager
:使用Hibernate版本进行持久化数据时使用 。
-
-
-
TransactionDefinition
:它是事务的定义信息对象。方法如下:String getName()
:获取事务对象名称。int getIsolationLevel()
:获取事务隔离级别。int getPropagationBehavior()
:获取事务传播行为。int getTimeout()
:获取事务超时时间。默认为-1
,即没有超时限制,如果有,以秒设置。boolean isReadOnly()
:获取事务是否只读。
-
TransactionStatus
:此接口提供的是事务具体的运行状态,方法如下:void flush()
:刷新事务。boolean hasSavapoint()
:获取是否存在存储点。boolean isCompleted()
:获取事务是否完成。boolean isNewTransaction()
:获取是否为新事务。boolean isRollbackOnly()
:获取事务是否回滚。void setRollbackOnly()
:设置事务回滚。
2.Spring事务控制-XML配置:
事务管理器配置:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
配置事务的通知:
-
tx:advice
:标签配置事务通知。- 属性
id
:给事务通知起一个唯一标识。 - 属性
transaction-manager
:给事务通知提供一个事务管理器引用。
- 属性
-
在aop中配置切入点表达式,并且建立切入点表达式和事务通知的对应关系。
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.atfwus.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
-
配置事务的属性,在事务的通知
tx:advice
标签的内部使用<tx:attributes>
,<tx:method
:- 属性
name
:指定方法名称,可以使用通配符。 - 属性
isolation
:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。 - 属性
propagation
:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。 - 属性
read-only
:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。 - 属性
timeout
:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。 - 属性
rollback-for
:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。 - 属性
no-rollback-for
:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
- 属性
XML配置示例:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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="accountService" class="com.atfwus.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置持久层-->
<bean id="accountDao" class="com.atfwus.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case02"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.atfwus.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
3.Spring事务控制-注解配置:
步骤:
- 配置事务管理器。
- 开启spring对注解事务的支持。
- 在需要事务支持的地方使用
@Transactional
注解
开启注解支持:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.atfwus"></context:component-scan>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/case02"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
普通注解与纯注解:
- 普通注解
@Transactional
,属性与上述事务属性一致,如:@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
- 纯注解:
@EnableTransactionManagement
,在配置类中,配置事务管理器。
ATFWUS --Writing By 2020–04-23