0

I am using spring-data-jpa in one of my projects. In service layer, I have annotated a private method with @Transactional and also enabled @EnableTransactionManagement in application. When one of the save method of entities throws an exception, the rest of the entities which were saved before are not rolling back. BTW I am using PostgreSQL.

Please let me know if I am missing anything here.

CrazyCoder
  • 2,465
  • 8
  • 36
  • 57
  • "A private method" indicates that most likely [this is your problem](https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo). (Note the solution is a decade old and obsolete in its particulars, but the principle is the same.) – chrylis -cautiouslyoptimistic- Oct 04 '19 at 05:38
  • @chrylis Changing the method to the public worked. Thanks – CrazyCoder Oct 04 '19 at 09:40

2 Answers2

1

Spring transaction will only work with public method. As it need to inject code using proxy classes for transactions. So making your method public will resolve your issue. Have a look on documentation of proxy mechanism of spring.

Farooq Khan
  • 592
  • 4
  • 15
0

Spring by default will rollback only for Runtime Exceptions (https://docs.spring.io/spring/docs/2.5.x/reference/transaction.html#transaction-declarative).

If you want to rollback for any exception, you could try adding:

@Transactional(rollbackFor = Exception.class)
andre
  • 448
  • 1
  • 3
  • 8