When to use transactions in Spring with Hibernate?

Rihards picture Rihards · May 13, 2011 · Viewed 11.5k times · Source

Upgrading my project I'm thinking here about transactions.
Well, the thing is I'm not quite sure when should I use the transactions for my Hibernate queries in Spring.
Not that I completely don't understand what transactions are, I guess I do, but
Do I need to use transactions for a get* type queries just setting the read-only attribute?

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- all methods starting with 'get' are read-only -->
        <tx:method name="get*" read-only="true" />
        <!-- other methods use the default transaction settings -->
        <tx:method name="*" />
    </tx:attributes>
</tx:advice>

Is that efficient for get* queries?
Because, as far I think, using transactions should be done like for CREATE, UPDATE, DELETE and such queries.
Am I missing something here?

Answer

tjg184 picture tjg184 · May 13, 2011

Using transactions is somewhat dependent on the requirement.

Obviously, using transactions on UPDATE and DELETE operations makes sense. Using transactions on SELECT statements could be useful too if, for example, you needed to lock the record such that another thread/request would not change the read. This would generally be a business requirement.

At our company we do wrap all statements (i.e. SELECT, UPDATE, DELETE) in a transaction.

In addition, transactional management is really better suited at another layer in addition to the data level. Generally, transactions would match the business requirement. For example, if the requirement is to deposit money in an account, then some higher level class/code should be used to mark the entire method as transactional since that specific method needs to be completed as one unit (since there would likely be multiple database calls).

Spring has much to say about transactional management.