基于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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置业务层 -->
<bean id="accountService" class="com.yaku.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!-- 配置持久层 -->
<bean id="accountDao" class="com.yaku.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- spring中基于XML声明形式事务控制配置步骤
1.配置事务管理器
2.配置事务的通知
此时需要导入事务的约束 tx 和 aop的名称空间和约束
使用tx:advice标签配置事务通知
属性:id:事务的唯一标志
transaction-manager:引用事务管理器
3.配置AOP的通用切入点表达式
4.建立事务通知和切入点表达式的关系
5.配置事务的属性
在事务的通知内配置tx:advice
isolation:指定事务的隔离级别,默认值:default,表示使用数据库默认隔离级别
propagation:事务的传播行为,默认值:REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
read-only:用于指定事务是否只读.只有查询方法设置为true。默认值为false,表示读写。
no-rollback-for:用于指定一个异常,当产生该异常是事务不回滚,产生其他异常时回滚。没有默认值,表示任何异常都会滚。
rollback-for:用于指定一个异常,当产生该异常是事务回滚,产生其他异常时不回滚。没有默认值,表示任何异常都会滚。
timeout:用于指定事务的超时时间,默认值为-1,表示永不超时。单位为秒
-->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</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:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut id="pt1" expression="execution(* com.yaku.service..*.*(..))"/>
<!-- 建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
service
package com.yaku.service.impl;
import com.yaku.dao.IAccountDao;
import com.yaku.dao.impl.AccountDaoImpl;
import com.yaku.service.IAccountService;
import com.yaku.unity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class AccountServiceImpl implements IAccountService {
@Autowired
private AccountDaoImpl accountDao ;
@Override
public List<Account> findAllAccounts() {
return accountDao.findAllAccounts();
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
Account sourceName1 = accountDao.findAccountByName(sourceName);
Account cc = accountDao.findAccountByName(targetName);
sourceName1.setMoney(sourceName1.getMoney()-money);
cc.setMoney(cc.getMoney()+money);
accountDao.updateAccount(sourceName1);
int i = 1/0;
accountDao.updateAccount(cc);
}
@Override
public Account findAccountByName(String accountName) {
return accountDao.findAccountByName(accountName);
}
public void setAccountDao(AccountDaoImpl accountDao) {
this.accountDao = accountDao;
}
}
dao
package com.yaku.dao.impl;
import com.yaku.dao.IAccountDao;
import com.yaku.unity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Account> findAllAccounts() {
try{
return jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
}catch (Exception e){
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer id) {
try {
return jdbcTemplate.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
jdbcTemplate.update("insert into account(name,money) value(?,?)",account.getName(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
jdbcTemplate.update("update account set name = ? ,money = ? where id = ?",account.getName(),account.getName(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer id) {
try {
jdbcTemplate.update("delete from account where id = ?",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountByName(String accountName) {
try {
List<Account> query = jdbcTemplate.query("select * from account where name like ?", new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(query.size() == 0 || query == null)
return null;
if(query.size()>1)
throw new RuntimeException("结果集不唯一");
return query.get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
}
基于注解配置
<?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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.yaku"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- spring中基于注解形式事务控制配置步骤
1.配置事务管理器
2.开启spring对注解事务的支持
3.在需要事务支持的地方使用@Transaction注解
@Transaction写在类名前对当前类中所有方法配置,可以指写在方法名前对该方法进行配置
-->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
service
package com.yaku.service.impl;
import com.yaku.dao.IAccountDao;
import com.yaku.dao.impl.AccountDaoImpl;
import com.yaku.service.IAccountService;
import com.yaku.unity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {
@Autowired
private AccountDaoImpl accountDao ;
@Override
public List<Account> findAllAccounts() {
return accountDao.findAllAccounts();
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer id) {
accountDao.deleteAccount(id);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
Account sourceName1 = accountDao.findAccountByName(sourceName);
Account cc = accountDao.findAccountByName(targetName);
sourceName1.setMoney(sourceName1.getMoney()-money);
cc.setMoney(cc.getMoney()+money);
accountDao.updateAccount(sourceName1);
int i = 1/0;
accountDao.updateAccount(cc);
}
@Override
public Account findAccountByName(String accountName) {
return accountDao.findAccountByName(accountName);
}
public void setAccountDao(AccountDaoImpl accountDao) {
this.accountDao = accountDao;
}
}
纯注解配置
SpringConfig
package com.yaku.config;
import com.yaku.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@ComponentScan({"com.yaku"})
@Import({JdbcConfig.class,TransactionManager.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}
JdbcConfig
package com.yaku.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* 和连接数据库相关的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Bean
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(url);
return dataSource;
}
}
TransactionManager
package com.yaku.config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class TransactionManager {
@Bean("transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
jdbcConfig.properties
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=
jdbc.driver=com.mysql.jdbc.Driver