Donnerstag, 7. Mai 2009

Hibernate Transactions and Connection Pooling

After 2 years of Java development using hibernate I noticed that my understanding of hibernate sessions and transactions was completely wrong. I thought:
  • I can interact with the database within and without a transaction.
  • Performance is better without a transaction.
  • Inserting a single entity without a transaction is good thing.
  • I don't need to step into the details of connection pooling until performance issues occurs.
  • If I call session.close() the session is closed and hibernate takes care of open transactions
I got it all wrong. After a bit of rtfm'ing and testing I noticed:
  • Interaction with a database always requires a transaction in hibernate. There is a feature called auto-commit which opens a transaction before executing a statement and closes it immediately after execution of the statement. This behavior is causing performance issues if a huge amount of queries is executed(Lazy Collections). So if I'm working with hibernate, I have to define the scope of the transaction(s).
  • Performance difference between commit and rollback within a transaction which not issued any write access is really hard to measure - there is no real difference.
  • Inserting a single entity without a transaction is impossible.
  • [ INFO] 21:17:01 org.hibernate.connection.DriverManagerConnectionProvider:64 - Using Hibernate built-in connection pool (not for production use!)
  • If I call session.close() using built in connection pooling the last transaction is untouched and reused by the next session obtained by sessionFactory.openSession(). Worst case scenario is one day of inserts and updates and the next day a transaction.rollBack() causes a heavy data loss. Using an alternative connection pooling (eg C3p0) is a must do, not a nice to have.
I created a simple test project named 'de.rhauswald.learning.hibernate.transactions' and committed it to this repository.

3 Kommentare:

rob hat gesagt…

http://tnfstacc-code.googlecode.com/svn/trunk/de.rhauswald.learning.hibernate.transactions/src/de/rhauswald/learning/hibernate/transactions/TheInternet.javaThe internet doesn't weight anything!

Richard Hauswald hat gesagt…

@see:
http://tnfstacc-code.googlecode.com/svn/trunk/de.rhauswald.learning.hibernate.transactions/src-test/de/rhauswald/learning/hibernate/transactions/SharedInternetTestMethods.java

rob hat gesagt…

Ok, i see. You should furthermore apply the JUnit 4 "assertCompletelyDemagnetized(IInternet internet)" assertion.

  © Blogger template 'Morning Drink' by Ourblogtemplates.com 2008

Back to TOP