|
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
Features Transactions in a JPA World
Week 38 of our Performance Almanac
By: Alois Reitbauer
Sep. 20, 2010 01:52 PM
The use of transactions is a cornerstone when building database applications. However in our daily work, we often do not really care much about them. In many cases they are handled implicitly for us by the (J EE) container or application framework – such as Spring – we are using. We rely on these frameworks to do a lot of the heaving lifting around transactions. At a pure JPA level there is a lot of transaction-related logic going on under the hood. This article discusses transactions at the JPA and database (JDBC) layer and how they play together and affect the functionality and performance of our applications. JDBC and the Database The easiest way to achieve this isolation is to use the database – or the data we are working with – just for ourselves. So we are locking the database rows in which we are interested in order that no one else can modify them. This is referred to as pessimistic locking. It is called pessimistic locking because even the most optimistic performance engineer will worry about the performance if it is done the wrong way. The opposite approach would be optimistic locking – assuming that nobody will modify the data while we work on it and only ensuring that we can handle concurrent modifications properly. Every modern database provides a means to define which level of isolation we require. In Java they are exposed via JDBC. The golden rule is the higher the isolation the more performance impact we get. Let’s look at the different isolation levels starting from the lowest to the highest:
In addition to locks, explicit lock statements can be used to ensure repeatable read and serializable behavior of a database. However locks force other transactions to wait until the lock is released which may have an even higher performance impact. The whole transaction behavior is controlled via the JDBC layer of the application. We can use connection properties to specify the isolation level and also issue explicit locking statements if needed. Two worlds coming together In order to get a basic understanding how those layers work together let’s start with a simple code sample and look at the resulting execution trace for it. Here we simply read a user from the database public void loadOneObject (){ EntityManager em = factory.createEntityManager(); EntityTransaction t = em.getTransaction(); Query query = em.createQuery("select user from User user where user.id= :userID"); query.setParameter("userID", 1L); List users = query.getResultList(); for (User user : users){ user.getLastName(); } em.close (); } And here is what happens at the JPA and JDBC layers. We see that the interaction with the database happens in the getResultList method. Here the connection is acquired the statement is executed against the database and the ResultSet is traversed. Then the connection is returned back into the connection pool As a quick note I will be using Hibernate and MySQL for these examples. We could however use a different implementation as well. Transactions in JPA Let’s have a look at the example below. Here we are loading the same entity twice using a query. We have to use a query here as using the load method would result in a cache hit in the persistence context. Queries, however, are not cached by default. If you want to know more read this article on the Hibernate Query Cache. public void doubleLoad (){ EntityManager em = factory.createEntityManager(); Query query = em.createQuery("select user from User user where user.id= :userID"); query.setParameter("userID", 1L); User u = (User)query.getSingleResult(); // second query query = em.createQuery("select user from User user where user.id= :userID"); query.setParameter("userID", 1L); u = (User)query.getSingleResult(); em.close (); } Below we see a transaction trace of the above code. For both queries a call was made to the database. This was our intended behavior; so it is fine. However we also can see – marked in blue- that after the second query only the ID is read and not the value of lastname field. So why does this happen? Here we see the cache at work. It checks whether it has already loaded the object and if so it does not rebuild it again from the ResultSet. Rebuilding objects can have a significant performance impact; especially if there are a lot of eager-loading relations associated to it
Loading the Same Entity Twice Synchronization with the Database public void loadandModify (){ EntityManager em = factory.createEntityManager(); EntityTransaction t = em.getTransaction(); t.begin(); Query query = em.createQuery("select user from User user where user.id= :userID"); query.setParameter("userID", 1L); User user = (User)query.getSingleResult(); user.setLastName("A different name"); query = em.createQuery("select user from User user where user.lastName like 'test%'"); query.getResultList(); t.commit(); } Here we load an entity from the database, modify a field and then execute a range query for the lastName parameter. This now creates a difficult situation for the JPA provider. It needs to execute a query against the database. However, the state of the database is not the latest state of the application. The JPA framework therefore must flush the changed entities to the database first as shown below. In case queries and data updates are mixed throughout the code this may have a serious performance impact. Most likely this behavior will not be noticed during development, but will eventually lead to problems in production. The use of tracing solutions like dynaTrace helps to discover this kind of problems already early in development Are JPA transactions equal to Database Transactions? public void strangeCommit (){ EntityManager em = factory.createEntityManager(); EntityTransaction t = em.getTransaction(); Query query = em.createQuery("select user from User user where user.id= :userID"); query.setParameter("userID", 1L); User user = (User) query.getSingleResult(); user.setLastName("Another last name"); t.begin(); t.commit(); em.close (); } So when does a transaction in the database sense start then? Before talking about transactions we have to think about connections first. Having a database transaction requires us to hold a connection as transactions are always tied to connections. JPA providers offer several choices when a database connection is acquired and how long it is kept. There are three main possibilities:
Whichever approach you are using should not matter too much as the default transaction level will be read committed. However as soon as force your JPA provider to flush to the database while a transaction is not yet committed – like described above – you also force the EntityManager to keep a transaction, and thus a connection, open. Explicit Locking Optimistic locking is best achieved by defining a Version attribute in your entities. When entity changes are then synchronized with the database, SQL statements are generated that check whether the entity has been modified in the meantime leading to an OptimisticLockingException. The code below uses two EntityManagers which modify the same Entity. public void lockingEntities (){ EntityManager em1 = factory.createEntityManager(); EntityManager em2 = factory.createEntityManager(); em1.getTransaction().begin(); User user1 = em1.find(User.class, 1L); user1.setLastName(user1.getLastName() + "%%"); em2.getTransaction().begin(); User user2 = em2.find(User.class, 1L); user2.setLastName(user2.getLastName() + "!"); em2.getTransaction().commit(); em1.getTransaction().commit(); } As you can see in the trace below the second update fails as the SQL statement with the version property in the WHERE clause does not affect the expected number of rows. The alternative solution would be to use a pessimistic lock. The code below explicitly locks the Entity with a pessimistic write lock. public void pessimisticLockingEntities (){ EntityManager em1 = factory.createEntityManager(); em1.getTransaction().begin(); User user1 = em1.find(User.class, 1L); em1.lock(user1, LockModeType.PESSIMISTIC_WRITE); user1.setLastName("Other last name"); em1.getTransaction().commit(); } As shown below, this results in a “select for update” SQL statement on the database. As mentioned earlier, explicit locking like this may yield to sever performance impact as well as deadlocks. Conclusion Understanding the transactional behavior is a cornerstone of writing functionally-correct and high-performing database applications. Using a JPA framework can make transaction handling a lot easier. However there are some important details regarding object state and transaction management a developer has to be aware of in order to avoid unwanted behavior. If we require more direct control over transaction behavior, the JPA specification – and additionally vendor specific APIs – provide more fine-grained control. Related reading:
SOA World Latest Stories
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||