Spring Data MongoDB @事务失败

时间:2018-08-23 01:25:39

标签: spring-data-mongodb spring-transactions mongo-java-driver

有人可以告诉我为什么这个春季交易不能适当回滚吗?

我得到的错误是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available

这是我的存储库,其中有一个保存交易,该交易有意失败:

@Repository
public class TransactionalRepository {

    private final PlayerRepository playerRepository;

    @Autowired
    public TransactionalRepository(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public Player saveSuccess(Player player) {
        return playerRepository.save(player);
    }

    @Transactional
    public Player saveFail(Player player) {
        player.setName("FAIL"); // should not be saved in DB if transaction rollback is successful
        player = playerRepository.save(player);
        throw new IllegalStateException("intentionally fail transaction");
    }
}

这是测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTransactionApplicationTests {

    @Autowired
    public TransactionalRepository playerRepository;

    @Test
    public void contextLoads() {

        Player player = new Player();
        player.setId(UUID.randomUUID().toString());
        final String PLAYER_NAME = "new-"+player.getId().subSequence(0,8);
        player.setName(PLAYER_NAME);
        player = playerRepository.saveSuccess(player);

        try {
            player = playerRepository.saveFail(player);
        } catch (IllegalStateException e) {
            // this is supposed to fail
        }

        Assert.assertEquals(PLAYER_NAME, player.getName());
    }

}

Download all the code here if you want to see it run

1 个答案:

答案 0 :(得分:2)

与其他实现不同,Spring Data MongoDB模块默认不注册PlatformTransactionManager(如果不存在)。这取决于用户的配置,以避免非MongoDB 4.x服务器以及已经使用@Transactional的项目以及非MongoDB特定的事务管理器实现的错误。有关详细信息,请参阅reference documentation

只需将MongoTransactionManager添加到您的配置中。

@Bean
MongoTransactionManager txManager(MongoDbFactory dbFactory) {
    return new MongoTransactionManager(dbFactory);
}

您可能还想查看Spring Data Examples,并看看MongoDB transactions的那个。