Spring事务当中propagation=“REQUIRED“和PROPAGATION=“REQUIRES_NEW“的区别
3.propagation="REQUIRED"和PROPAGATION="REQUIRES_NEW"的区别
(官方)PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。
马克-to-win:当两个不同的pointcut之间涉及调用方法时,就涉及到事务传播属性。比如上面的方法updateRegister,如果它的属性是PROPAGATION_REQUIRED,则它会和调用它的方法login同属一个事务,如果是REQUIRES_NEW,则在不同的事务。当updateRegister已经提交之后updateRegisterWrong发生错误的时候,如果是REQUIRES_NEW,则updateRegister不会回滚,而如果是REQUIRED,则会回滚。注意下例,我们把两个方法故意放在两个pointcut里。看一下程序把REQUIRED变成REQUIRES_NEW以后的区别。
例 2.3.1
package service;
import java.sql.Types;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.INiutDAO;
import service.interfac.ILoginService;
public class LoginServiceImpl implements ILoginService {
@Resource
private JdbcTemplate jt;
private INiutDAO iNiutDAO;
public void setINiutDAO(INiutDAO iNiutDAO) {
this.iNiutDAO = iNiutDAO;
}
public void login() {
iNiutDAO.daoUpdateRegister(13,1);
System.out.println("successfully update 1");
updateRegisterWrong(19,2);
System.out.println("successfully update 2");
}
public void updateRegisterWrong(int age,int id) {
String sql = "UPDATE register SET age=? WWWWWWW id=?";
Object params[] = new Object[] { new Integer(age),
new Integer(id) };
int type[] = new int[] { Types.INTEGER , Types.INTEGER };
jt.update(sql, params, type);
}
}
<?xml version="1.0" encoding="UTF-8"?>
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
>
package com;
import java.sql.Types;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
public class NiutDAO implements INiutDAO {
@Resource
private JdbcTemplate jt;
public void daoUpdateRegister(int age,int id) {
String sql = "UPDATE register SET age=? WHERE id=?";
Object params[] = new Object[] { new Integer(age),
new Integer(id) };
int type[] = new int[] { Types.INTEGER , Types.INTEGER };
jt.update(sql, params, type);
}
}
package com;
public interface INiutDAO {
public void daoUpdateRegister(int age,int id);
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44591615/article/details/109206459