Skip to content

Instantly share code, notes, and snippets.

@CoderInOne
Last active April 25, 2019 09:55
Show Gist options
  • Save CoderInOne/495249c44275a90cc82e0672fe5e3d90 to your computer and use it in GitHub Desktop.
Save CoderInOne/495249c44275a90cc82e0672fe5e3d90 to your computer and use it in GitHub Desktop.
Spring的事务传播机制,以Propagation.REQUIRED为例 参考文章:https://www.ibm.com/developerworks/cn/education/opensource/os-cn-spring-trans/index.html
@Configuration
@EnableTransactionManagement
@Component
public class Committer {
// define data source
private final DataSource ds = DataSourceBuilder
.create()
.username("root")
.password("123456")
.url("jdbc:mysql://localhost:3306/test")
.driverClassName("com.mysql.jdbc.Driver")
.build();
@Bean
@Primary
public PlatformTransactionManager txMgr() {
return new DataSourceTransactionManager(ds);
}
// get mybatis mapper
private UserMapper getUserMapper() {
try {
SqlSessionTemplate template = sqlSessionTemplate(loadSqlSessionFactory(ds));
return template.getMapper(UserMapper.class);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
// outer transaction
@Transactional(propagation = Propagation.REQUIRED)
public void outerTx() {
String aUser = "user_required";
insertUser(aUser);
try {
innerTx(aUser);
}
catch (RuntimeException ex) {
ex.printStackTrace();
}
}
// inner transaction
@Transactional(propagation = Propagation.REQUIRED)
public void innerTx(String username) {
getUserMapper().createLog("creating user:" + username);
throw new RuntimeException("mock exception");
}
private void insertUser(String username) {
getUserMapper().insert(new User(username));
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Committer.class)
public class TestConfigTest {
@Autowired
private Committer committer;
@Test
public void testPropagateRequired() {
committer.outerTx();
}
}
@CoderInOne
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment