我正在做一些测试以了解 Spring 3 中 @Transactional 的行为。不过,它并没有像我预期的那样工作。如果有一个使用 Propagation.REQUIRED 的方法调用另一个使用 Propagation.REQUIRES_NEW 的方法,那么第二种方法是否能够从数据库中检索第一种方法插入的数据?
已编辑:我在@Transaction中看到未提交的更改,这是我的(令人讨厌的)代码。
@Service
public class FeedManager {
@Autowired
JdbcTemplate jdbcTemplate;
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public boolean createFeed(Feed feed, boolean anonymizeIt) {
String query = "INSERT INTO feed (name, url, is_active) values (?, ?, ?)";
int rowsAffected = jdbcTemplate.update(query, feed.getName(), feed.getUrl(), feed.isActive());
boolean success = (rowsAffected == 1);
if (anonymizeIt) {
success = success && this.anonymizeFeedName(feed);
}
return success;
}
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public boolean anonymizeFeedName(Feed feed) {
String query = "UPDATE feed set name = ? where name = ?";
int rowsAffected = jdbcTemplate.update(query, feed.getName() + (new Date()).toString(), feed.getName());
boolean success = (rowsAffected == 1);
return success;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:mrpomario/springcore/jdbc/jdbc-testenv-config.xml")
public class TransactionalTest {
@Autowired
FeedManager feedManager;
Feed feed;
@Before
public void setup() {
feed = new Feed("RSS", "http://www.feedlink.com", true);
}
@Test
public void test_Create() {
assertTrue(feedManager.createFeed(feed, false));
}
@Test
public void test_Anonymize() {
assertTrue(feedManager.anonymizeFeedName(feed));
}
@Test
public void test_Create_And_Anonymize() {
Feed feedo = new Feed("AnotherRSS", "http://www.anotherfeedlink.com", true);
assertTrue(feedManager.createFeed(feedo, true));
}
}