【问题标题】:Use transaction for multiple save使用事务进行多次保存
【发布时间】:2014-11-21 15:09:42
【问题描述】:

我需要在一个事务中在我的服务中保存更多实体 - 如果一个保存失败,则不应保存任何内容。我尝试使用@Transactional,但它不起作用,或者我不知道如何使用它:) 保存正确的记录,不保存错误的记录,我都不需要保存。我怎样才能做到这一点?

我的代码:

public interface MyRecordRepository extends JpaRepository<Record, Long>,
        QueryDslPredicateExecutor<Record> {

}

@Service
public class MyPersisterServiceImpl implements MyPersisterService {...
    @Autowired
    private MyRepository myRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRecords(List<Record> recordList) {
        for(Record r : recordList){
            myRepository.save(record);
        }
    }
...


@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
... // other annotations
public class Application extends SpringBootServletInitializer {
...

我的环境:带有 Spring 数据的 Spring 4.0.7、querydsl、hibernate、apache tomcat 8、java 8。

谢谢

【问题讨论】:

    标签: transactions spring-data rollback


    【解决方案1】:

    看起来 aspectj 配置有问题,因为在代理模式下它按预期工作......我暂时将此问题标记为已解决。

    【讨论】:

      【解决方案2】:

      我使我的交易适用于多次保存,如下所示:

      @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
      public void service-method( ) throws RestServiceException,Exception{
      for(entity,entities) {
           repository1.save(entity)
       }
      for(entity2,entities2) {
           repository2.save(entity2)
      }
      throw new Exception();
      }
      

      希望有帮助。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2018-08-16
      相关资源
      最近更新 更多