Last active
April 25, 2019 09:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RunWith(SpringJUnit4ClassRunner.class) | |
@ContextConfiguration(classes = Committer.class) | |
public class TestConfigTest { | |
@Autowired | |
private Committer committer; | |
@Test | |
public void testPropagateRequired() { | |
committer.outerTx(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考文章:https://www.ibm.com/developerworks/cn/education/opensource/os-cn-spring-trans/index.html