Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional read-only mode rollback behaviour

I have some service layer method with @Transactional(readOnly=true) and this method causes some RuntimeException quite often (let's say it is some NotFoundException exception).

I'm using ORM Hibernate also for the DB interaction process.

Is it legal pattern to do so?

What is the default behaviour in this case in sense of "roll-back" behaviour? Can it influence somehow badly on connections's state or lead to any problems?


It isn't something like "why not try it by your self?". I have a suspicion that this could lead to the Transaction rolled back because it has been marked as rollback-only error in the same method after some number of exceptions. This could be very specific JDBC PostgreSQL driver error. That is why I'm wondering about this design in general: is it something legal or illegal to do so?

like image 492
Andremoniy Avatar asked May 02 '17 16:05

Andremoniy


1 Answers

So as far as I understand, you are worried about the roll-back. In this case a readOnly is a select statement and usually there is nothing to roll-back from a read. The only place where this is handy is when you read under a lock and when the transaction finishes you release that lock.

AFAIK readOnly will set the flushmode to FlushMode.NEVER and that is good and bad at the same time. Good, because there will no dirty checking, as described here. Bad because if you call a read/write transaction within a readOnly transaction, the transaction will silently fail to commit because the session is not flushed. This is easily testable btw - and I hope things have not changed since I've tried this.

Then there is the pool of connections. I know that C3P0's default policy is to rollback any uncommitted work. The flag to control this is autoCommitOnClose.

Then there is this link about readOnly and postgres - which I have not worked with and can't really tell my opinion on.

Now to your point about Transaction rolled back because it has been marked as rollback-only. For a readOnly transaction there might be nothing to roll-back as I said before, so this really depends on how you chain your @Transactional methods IMO.

like image 156
Eugene Avatar answered Oct 31 '22 06:10

Eugene