[英]Spring Data JPA Rollback If Save Method Throw Exception
Problem solved : Go to last entry问题已解决:转到最后一个条目
I am trying to test my method's rollback function if any exception has thrown from save method of crudrepository.如果从 crudrepository 的 save 方法抛出任何异常,我正在尝试测试我的方法的回滚功能。 I have a main loop which scans my file and for each row then insert a record into table.
我有一个主循环,它扫描我的文件,然后为每一行插入一条记录到表中。 I realized that when any exception occured, loop breaks but rollback operation doesn't work.
我意识到当发生任何异常时,循环会中断但回滚操作不起作用。 What am I missing?
我错过了什么? Thanks in advance
提前致谢
@Component
public class ExcelReader {
@PostConstruct
@Transactional
public void openExcel() throws IOException {
int insertedRowCount = 0;
int updatedRowCount = 0;
int exceptionRowCount = 0;
//some codes
while (true) {
//some logic
City2CityEntity city2CityEntity = new City2CityEntity();
city2CityRepository.save(city2CityEntity);
if(insertedRowCount == 500){
throw new RuntimeException();
}
insertedRowCount++;
}
}
System.out.println(insertedRowCount + " number of rows inserted");
System.out.println(updatedRowCount + " number of rows skipped");
System.out.println(exceptionRowCount + " couldn't inserted");
}
}
@Repository
public interface City2CityRepository extends CrudRepository<City2CityEntity, Long> {
Iterable<City2CityEntity> findAll();
City2CityEntity findByCompanyAndOrgAndDst(String company, String org, String dst);
}
@Entity
@Table(name = "xxx_berkin_city2city", schema = "CRANE_AT", catalog = "")
public class City2CityEntity {
//getter setters and fields
}
After 501. record inserted, I threw an exception. 501.记录插入后,抛出异常。
@Transactional(rollbackFor = Exception.class)
This is the answer above.这是上面的答案。 I found here: What is difference between @Transactional(rollbackFor = Exception.class) and @Transactional(propagation=Propagation.REQUIRED)
我在这里找到: @Transactional(rollbackFor = Exception.class) 和 @Transactional(propagation=Propagation.REQUIRED) 之间有什么区别
Edit : I solved problem.编辑:我解决了问题。 I removed @PostConstruct annotation on top of openExcel function.
我删除了 openExcel 函数之上的@PostConstruct注释。 Then used ExcelReader bean with using applicationContext.getBean() method from main class.
然后使用 ExcelReader bean 和主类中的 applicationContext.getBean() 方法。 Now everything works perfectly.
现在一切正常。 I didn't have to use any parameter for @Transactional annotation anymore.
我不必再为 @Transactional 注释使用任何参数。
@SpringBootApplication
@EnableConfigurationProperties({FileProperties.class, TargetProperties.class})
public class Application {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
ExcelReader excelReader = applicationContext.getBean(ExcelReader.class);
try {
excelReader.openExcel();
} catch (IOException e) {
e.printStackTrace();
}
}
}
尝试使用下一个:
@Transactional(rollbackFor = Exception.class) // your exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.