首页 > IT职业 > IT生活 > Spring【DAO模块】知识要点
<!--扫描注解--> <!-- 2. 创建JdbcTemplate对象 -->
- userDao
```java
package bb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
* Created by ozc on 2017/5/10.
*/
@Component
public class UserDao implements IUser {
//使用Spring的自动装配
@Autowired
private JdbcTemplate template;
@Override
public void save() {
String sql = "insert into user(name,password) values('zhoggucheng','123')";
template.update(sql);
}
}
@Test
public void test33() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bb/bean.xml");
UserDao userDao = (UserDao) ac.getBean("userDao");
userDao.save();
} 
看了上面的事务属性,没有接触过的其实就这么一个:propagation = Propagation.REQUIRED事务的传播行为。
事务传播行为的属性有以下这么多个,常用的就只有两个:

现在有一个日志类,它的事务传播行为是Propagation.REQUIRED
Class Log{
Propagation.REQUIRED
insertLog();
}
Propagation.REQUIRED
Void saveDept(){
insertLog();
saveDept();
} saveDept()本身就存在着一个事务,当调用insertLog()的时候,insertLog()的事务会加入到saveDept()事务中
也就是说,saveDept()方法内始终是一个事务,如果在途中出现了异常,那么insertLog()的数据是会被回滚的【因为在同一事务内】
Void saveDept(){
insertLog(); // 加入当前事务
.. 异常, 会回滚
saveDept();
} 现在有一个日志类,它的事务传播行为是Propagation.REQUIRED_NEW
Class Log{
Propagation.REQUIRED
insertLog();
}
Propagation.REQUIRED
Void saveDept(){
insertLog();
saveDept();
} 当执行到saveDept()中的insertLog()方法时,insertLog()方法发现 saveDept()已经存在事务了,insertLog()会独自新开一个事务,直到事务关闭之后,再执行下面的方法
如果在中途中抛出了异常,insertLog()是不会回滚的,因为它的事务是自己的,已经提交了
Void saveDept(){
insertLog(); // 始终开启事务
.. 异常, 日志不会回滚
saveDept();
} 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/658/viewspace-2799838/ ,如需转载,请注明出处,否则将追究法律责任。