• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When do JPA and Hibernate Need Transactions?

 
Siegfried Heintze
Ranch Hand
Posts: 408
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been google searching and finally fixed my problem by adding a transaction.

I noticed a sample app at http://forum.springframework.org/showthread.php?t=29761 that did not start a transaction before saving but then the posting date was 2004. (I guess I should see if this sample works -- I have not yet).

When do I need to start a transaction and what kind?

Do I always need to start a transaction even if it is a simple SELECT statement?

For JPA? For Hibernate too?


With my JPA example, I tried starting a transaction with org.springframework.orm.jpa.JpaTransactionManager and received an error message from spring that I needed to start a spring transaction!

After failing figure out how to make the transactionManager create a transaction in my JPA example, I finally got my example to work with org.springframework.transaction.support.TransactionTemplate.

I got the impression from "Spring In Action" (2nd ed) that transactionManager should have worked and that TransactionTemplate was overkill and there should be some simpler approaches. Is that true?

Oh yeah! I forgot to ask:

This code is really ugly! How can I declare result so that it is in the scope of the function getEmployees?

Assuming I'm stuck with transactionTemplates, is there a better way?
Assuming I'm not stuck with transactionTemplates, what would it look like?



Thanks,
Siegfried
[ January 04, 2008: Message edited by: Siegfried Heintze ]
 
Mike Keith
author
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the cool features that JPA includes is the ability to do any read query outside the scope of a transaction. You never need to start a transaction if you only want to access data, and then if you do need to change it then you can do so and then later merge it into a persistence context within a transaction.

My personal favorite way of managing transactions in Spring is by using the @Transactional annotation. (You just add <tx:annotation-driven/> in your application context file.) Makes for simple and elegant declarative transactions.
 
Siegfried Heintze
Ranch Hand
Posts: 408
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found an example http://static.springframework.org/spring/docs/2.0.x/reference/transaction.html .

Is this what I am looking for?

Do I put @Transactional on the DAO? If so, does the transaction start and end with each function call of the DAO?

Thanks,
Siegfried
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic