Robert Munteanu
Robert Munteanu

Reputation: 68268

Validating that all JDBC calls happen within a transaction

How can I validate that all JDBC access happens on an active transaction, i.e. java.sql.Connection.getAutoCommit() always return false?

I'm using Spring for transaction management ( @Transactional ) and Hibernate for data access.


Update: What happens is that some Hibernate access is performed without the service method being annotated with @Transactional. That's what I want to be notified of.

Update 2: Code sample

It's possible to call the following code:

public ServiceImpl implements Service {

     // missing @Transactional
     public List<String> getSomeIds() {
           return getDao().getSomeIds();
     }
}

Upvotes: 3

Views: 421

Answers (3)

Alex Beardsley
Alex Beardsley

Reputation: 21173

You actually shouldn't need to do this, since according to the @Transactional documentation, section 9.5.6.1:

The default @Transactional settings are:

 The propagation setting is PROPAGATION_REQUIRED
 ....

PROPAGATION_REQUIRED means:

Support a current transaction, create a new one if none exists.

EDIT: Your best bet is probably to do what @duffymo said in his comment:

You can write an aspect to expressly forbid DAO access outside the service layer if you wish.

Upvotes: 1

qnoid
qnoid

Reputation: 2376

One way I can think of is to implement and register a dummy JDBC Driver to act as an interceptor between the statements you want to monitor as well as keep a log of when Connection#setAutoCommit() and Connection#commit() is called to know the boundaries of the transaction.

Upvotes: 2

duffymo
duffymo

Reputation: 308753

Use PROPAGATION_REQUIRED on all persistent methods.

Upvotes: 2

Related Questions