Archive for October, 2007

CHAPTER 10 Transactions and concurrency context is suspended

Monday, October 22nd, 2007

CHAPTER 10 Transactions and concurrency context is suspended for the duration of this method. The SELECT is effectively executed in autocommit mode. (Internally, an autocommitted JDBC connection is assigned to serve this Session.) Finally, you need to know that the default FlushMode of a Session changes when no transaction is in progress. The default behavior, FlushMode.AUTO, results in a synchronization before every HQL, SQL, or Criteria query. This is bad, of course, because DML UPDATE, INSERT, and DELETE operations execute in addition to a SELECT for the query. Because you re working in autocommit mode, these modifications are permanent. Hibernate prevents this by disabling automatic flushing when you use a Session outside of transaction boundaries. You then have to expect that queries may return stale data or data that is conflicting with the state of data in your current Session effectively the same issue you have to deal with when FlushMode.MANUAL is selected. We ll get back to nontransactional data access in the next chapter, in our discussion of conversations. You should consider autocommit behavior a feature that you’d possibly use in conversations with Java Persistence or EJBs, and when wrapping programmatic transaction boundaries around all data access events would be difficult (in a desktop application, for example). In most other cases, autocommit results in systems that are difficult to maintain, with now performance or scalability benefit. (In our opinion, RDBMS vendors should not enable autocommit by default. SQL query consoles and tools should enable autocommit mode on a connection, when necessary.) 10.4 Summary In this chapter, you learned about transactions, concurrency, isolation, and locking. You now know that Hibernate relies on the database concurrency control mechanism but provides better isolation guarantees in a transaction, thanks to automatic versioning and the persistence context cache. You learned how to set transaction boundaries programmatically with the Hibernate API, JTA UserTransaction, and the JPA EntityTransaction interface. We also looked at transaction assembly with EJB 3.0 components and how you can work nontransactionally with autocommit mode.
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Nontransactional data access tion isn t (Affordable web design) already in that

Sunday, October 21st, 2007

Nontransactional data access tion isn t already in that mode. The previous code examples now work predictably, and the JDBC driver wraps a short transaction around every SQL statement that is send to the database with the implications we listed earlier. In which scenarios would you enable the autocommit mode in Hibernate, so that you can use a Session without beginning and ending a transaction manually? Systems that benefit from autocommit mode are systems that require on-demand (lazy) loading of data, in a particular Session and persistence context, but in which it is difficult to wrap transaction boundaries around all code that might trigger on-demand data retrieval. This is usually not the case in web applications that follow the design patterns we discuss in chapter 16. On the other hand, desktop applications that access the database tier through Hibernate often require on-demand loading without explicit transaction boundaries. For example, if you double-click on a node in a Java Swing tree view, all children of that node have to be loaded from the database. You’d have to wrap a transaction around this event manually; the autocommit mode is a more convenient solution. (Note that we are not proposing to open and close Sessions on demand!) 10.3.3 Optional transactions with JTA The previous discussion focused on autocommit mode and nontransactional data access in an application that utilizes unmanaged JDBC connections, where Hibernate manages the connection pool. Now imagine that you want to use Hibernate in a Java EE environment, with JTA and probably also CMT. The connection. autocommit configuration option has no effect in this environment. Whether autocommit is used depends on your transaction assembly. Imagine that you have an EJB session bean that marks a particular method as nontransactional: @Stateless public class ItemFinder { @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public Item findItemById(Long id) { Session s = getSessionFactory().openSession(); Item item = (Item) s.get(Item.class, id); s.close(); return item; } } The findItemById() method produces an immediate SQL SELECT that returns the Item instance. Because the method is marked as not supporting a transaction context, no transaction is started for this operation, and any existing transaction
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Best web design - CHAPTER 10 Transactions and concurrency turns off the

Saturday, October 20th, 2007

CHAPTER 10 Transactions and concurrency turns off the autocommit mode on this connection with setAutoCommit(false). This effectively starts a JDBC transaction! 3 The SELECT is executed inside this JDBC transaction. The Session is closed, and the connection is returned to the pool and released by Hibernate Hibernate calls close() on the JDBC Connection. What happens to the uncommitted transaction? The answer to that question is, It depends! The JDBC specification doesn t say anything about pending transactions when close() is called on a connection. What happens depends on how the vendors implement the specification. With Oracle JDBC drivers, for example, the call to close() commits the transaction! Most other JDBC vendors take the sane route and roll back any pending transaction when the JDBC Connection object is closed and the resource is returned to the pool. Obviously, this won t be a problem for the SELECT you ve executed, but look at this variation: Session session = getSessionFactory().openSession(); Long generatedId = session.save(item); session.close(); This code results in an INSERT statement, executed inside a transaction that is never committed or rolled back. On Oracle, this piece of code inserts data permanently; in other databases, it may not. (This situation is slightly more complicated: The INSERT is executed only if the identifier generator requires it. For example, an identifier value can be obtained from a sequence without an INSERT. The persistent entity is then queued until flush-time insertion which never happens in this code. An identity strategy requires an immediate INSERT for the value to be generated.) We haven t even touched on autocommit mode yet but have only highlighted a problem that can appear if you try to work without setting explicit transaction boundaries. Let s assume that you still think working without transaction demarcation is a good idea and that you want the regular autocommit behavior. First, you have to tell Hibernate to allow autocommitted JDBC connections in the Hibernate configuration:
true With this setting, Hibernate no longer turns off autocommit when a JDBC connection is obtained from the connection pool it enables autocommit if the connec
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

Nontransactional data access Many more issues must be

Friday, October 19th, 2007

Nontransactional data access Many more issues must be considered when you introduce nontransactional data access in your application. We ve already noted that introducing a new type of transaction, namely read-only transactions, can significantly complicate any future modification of your application. The same is true if you introduce nontransactional operations. You would then have three different kinds of data access in your application: in regular transactions, in read-only transactions, and now also nontransactional, with no guarantees. Imagine that you have to introduce an operation that writes data into a unit of work that was supposed to only read data. Imagine that you have to reorganize operations that were nontransactional to be transactional. Our recommendation is to not use the autocommit mode in an application, and to apply read-only transactions only when there is an obvious performance benefit or when future code changes are highly unlikely. Always prefer regular ACID transactions to group your data-access operations, regardless of whether you read or write data. Having said that, Hibernate and Java Persistence allow nontransactional data access. In fact, the EJB 3.0 specification forces you to access data nontransactionally if you want to implement atomic long-running conversations. We ll approach this subject in the next chapter. Now we want to dig a little deeper into the consequences of the autocommit mode in a plain Hibernate application. (Note that, despite our negative remarks, there are some good use cases for the autocommit mode. In our experience autocommit is often enabled for the wrong reasons and we wanted to wipe the slate clean first.) 10.3.2 Working nontransactionally with Hibernate Look at the following code, which accesses the database without transaction boundaries: Session session = sessionFactory.openSession(); session.get(Item.class, 123l); session.close(); By default, in a Java SE environment with a JDBC configuration, this is what happens if you execute this snippet: 1 A new Session is opened. It doesn t obtain a database connection at this point. 2 The call to get() triggers an SQL SELECT. The Session now obtains a JDBC Connection from the connection pool. Hibernate, by default, immediately
If you are in need for chaep and reliable webhost to host your website, our recommendation is http web server services.

CHAPTER 10 Transactions and concurrency An application, by (Web hosting isp)

Thursday, October 18th, 2007

CHAPTER 10 Transactions and concurrency An application, by definition, always executes a planned sequence of statements. It seems reasonable that you therefore always create transaction boundaries to group your statements into units that are atomic. Therefore, the autocommit mode has no place in an application. 10.3.1 Debunking autocommit myths Many developers still like to work with an autocommit mode, often for reasons that are vague and not well defined. Let s first debunk a few of these reasons before we show you how to access data nontransactionally if you want (or have) to: Many application developers think they can talk to a database outside of a transaction. This obviously isn t possible; no SQL statement can be send to a database outside of a database transaction. The term nontransactional data access means there are no explicit transaction boundaries, no system transaction, and that the behavior of data access is that of the autocommit mode. It doesn t mean no physical database transactions are involved. If your goal is to improve performance of your application by using the autocommit mode, you should think again about the implications of many small transactions. Significant overhead is involved in starting and ending a database transaction for every SQL statement, and it may decrease the performance of your application. If your goal is to improve the scalability of your application with the auto- commit mode, think again: A longer-running database transaction, instead of many small transactions for every SQL statement, may hold database locks for a longer time and probably won t scale as well. However, thanks to the Hibernate persistence context and write-behind of DML, all write locks in the database are already held for a short time. Depending on the isolation level you enable, the cost of read locks is likely negligible. Or, you may use a DBMS with multiversion concurrency that doesn t require read locks (Oracle, PostgreSQL, Informix, Firebird), because readers are never blocked by default. Because you re working nontransactionally, not only do you give up any transactional atomicity of a group of SQL statements, but you also have weaker isolation guarantees if data is modified concurrently. Repeatable reads based on read locks are impossible with autocommit mode. (The persistence context cache helps here, naturally.)
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

Nontransactional data access Session session (Web design tools) = getSessionFactory().openSession(); Transaction

Wednesday, October 17th, 2007

Nontransactional data access Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); User u = (User) session.get(User.class, 123); session.lock(u, LockMode.FORCE); u.getDefaultBillingDetails().setOwner(”John Doe”); tx.commit(); session.close(); Any concurrent unit of work that works with the same User row now knows that this data was modified, even if only one of the values that you d consider part of the whole aggregate was modified. This technique is useful in many situations where you modify an object and want the version of a root object of an aggregate to be incremented. Another example is a modification of a bid amount for an auction item (if these amounts aren t immutable): With an explicit version increment, you can indicate that the item has been modified, even if none of its value-typed properties or collections have changed. The equivalent call with Java Persistence is em.lock(o, LockModeType.WRITE). You now have all the pieces to write more sophisticated units of work and create conversations. We need to mention one final aspect of transactions, however, because it becomes essential in more complex conversations with JPA. You must understand how autocommit works and what nontransactional data access means in practice. 10.3 Nontransactional data access Many DBMSs enable the so called autocommit mode on every new database connection by default. The autocommit mode is useful for ad hoc execution of SQL. Imagine that you connect to your database with an SQL console and that you run a few queries, and maybe even update and delete rows. This interactive data access is ad hoc; most of the time you don t have a plan or a sequence of statements that you consider a unit of work. The default autocommit mode on the database connection is perfect for this kind of data access after all, you don t want to type begin a transaction and end a transaction for every SQL statement you write and execute. In autocommit mode, a (short) database transaction begins and ends for each SQL statement you send to the database. You re working effectively nontransactionally, because there are no atomicity or isolation guarantees for your session with the SQL console. (The only guarantee is that a single SQL statement is atomic.)
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Http web server - CHAPTER 10 Transactions and concurrency By default, load()

Tuesday, October 16th, 2007

CHAPTER 10 Transactions and concurrency By default, load() and get() use LockMode.NONE. A LockMode.READ is most useful with session.lock() and a detached object. Here s an example: Item item = … ; Bid bid = new Bid(); item.addBid(bid); … Transaction tx = session.beginTransaction(); session.lock(item, LockMode.READ); tx.commit(); This code performs a version check on the detached Item instance to verify that the database row wasn t updated by another transaction since it was retrieved, before saving the new Bid by cascade (assuming the association from Item to Bid has cascading enabled). (Note that EntityManager.lock() doesn t reattach the given entity instance it only works on instances that are already in managed persistent state.) Hibernate LockMode.FORCE and LockModeType.WRITE in Java Persistence have a different purpose. You use them to force a version update if by default no version would be incremented. Forcing a version increment If optimistic locking is enabled through versioning, Hibernate increments the version of a modified entity instance automatically. However, sometimes you want to increment the version of an entity instance manually, because Hibernate doesn t consider your changes to be a modification that should trigger a version increment. Imagine that you modify the owner name of a CreditCard: Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); User u = (User) session.get(User.class, 123); u.getDefaultBillingDetails().setOwner(”John Doe”); tx.commit(); session.close(); When this Session is flushed, the version of the BillingDetail s instance (let s assume it s a credit card) that was modified is incremented automatically by Hibernate. This may not be what you want you may want to increment the version of the owner, too (the User instance). Call lock() with LockMode.FORCE to increment the version of an entity instance:
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Controlling concurrent access locks. This is (Web host music) almost always

Monday, October 15th, 2007

Controlling concurrent access locks. This is almost always a performance bottleneck; every data access involves additional lock checks to a synchronized lock manager. Optimistic locking, however, is the perfect concurrency control strategy and performs well in long-running conversations. Depending on your conflict-resolution options (that is, if you had enough time to implement merge changes), your application users are as happy with it as with blocked concurrent access. They may also appreciate not being locked out of particular screens while others look at the same data. Java Persistence defines LockModeType.READ for the same purpose, and the EntityManager also has a lock() method. The specification doesn t require that this lock mode is supported on nonversioned entities; however, Hibernate supports it on all entities, because it defaults to a pessimistic lock in the database. The Hibernate lock modes Hibernate supports the following additional LockModes: LockMode.NONE Don t go to the database unless the object isn t in any cache. LockMode.READ Bypass all caches, and perform a version check to verify that the object in memory is the same version that currently exists in the database. LockMode.UPDGRADE Bypass all caches, do a version check (if applicable), and obtain a database-level pessimistic upgrade lock, if that is supported. Equivalent to LockModeType.READ in Java Persistence. This mode transparently falls back to LockMode.READ if the database SQL dialect doesn t support a SELECT … FOR UPDATE option. LockMode.UPDGRADE_NOWAIT The same as UPGRADE, but use a SELECT … FOR UPDATE NOWAIT, if supported. This disables waiting for concurrent lock releases, thus throwing a locking exception immediately if the lock can t be obtained. This mode transparently falls back to LockMode.UPGRADE if the database SQL dialect doesn t support the NOWAIT option. LockMode.FORCE Force an increment of the objects version in the database, to indicate that it has been modified by the current transaction. Equivalent to LockModeType.WRITE in Java Persistence. LockMode.WRITE Obtained automatically when Hibernate has written to a row in the current transaction. (This is an internal mode; you may not specify it in your application.)
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.

Web hosts - CHAPTER 10 Transactions and concurrency This example is

Sunday, October 14th, 2007

CHAPTER 10 Transactions and concurrency This example is simplified, but it s enough to illustrate how a unit of work that mixes entity and scalar reads is vulnerable to nonrepeatable reads, if the database transaction isolation level is read committed. Instead of switching all database transactions into a higher and nonscalable isolation level, you obtain stronger isolation guarantees when necessary with the lock() method on the Hibernate Session: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item i = (Item) session.get(Item.class, 123); session.lock(i, LockMode.UPGRADE); String description = (String) session.createQuery(”select i.description from Item i” + ” where i.id = :itemid”) .setParameter(”itemid”, i.getId() ) .uniqueResult(); tx.commit(); session.close(); Using LockMode.UPGRADE results in a pessimistic lock held on the database for the row(s) that represent the Item instance. Now no concurrent transaction can obtain a lock on the same data that is, no concurrent transaction can modify the data between your two reads. This can be shortened as follows: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item i = (Item) session.get(Item.class, 123, LockMode.UPGRADE); … A LockMode.UPGRADE results in an SQL SELECT … FOR UPDATE or similar, depending on the database dialect. A variation, LockMode.UPGRADE_NOWAIT, adds a clause that allows an immediate failure of the query. Without this clause, the database usually waits when the lock can t be obtained (perhaps because a concurrent transaction already holds a lock). The duration of the wait is database-dependent, as is the actual SQL clause. FAQ Can I use long pessimistic locks? The duration of a pessimistic lock in Hibernate is a single database transaction. This means you can t use an exclusive lock to block concurrent access for longer than a single database transaction. We consider this a good thing, because the only solution would be an extremely expensive lock held in memory (or a so-called lock table in the database) for the duration of, for example, a whole conversation. These kinds of locks are sometimes called offline
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Controlling concurrent access detected. This is the equivalent (Web hosts)

Sunday, October 14th, 2007

Controlling concurrent access detected. This is the equivalent of the native StaleObjectStateException in Hibernate and should be treated accordingly. We ve now covered the basic isolation levels of a database connection, with the conclusion that you should almost always rely on read-committed guarantees from your database. Automatic versioning in Hibernate and Java Persistence prevents lost updates when two concurrent transactions try to commit modifications on the same piece of data. To deal with nonrepeatable reads, you need additional isolation guarantees. 10.2.3 Obtaining additional isolation guarantees There are several ways to prevent nonrepeatable reads and upgrade to a higher isolation level. Explicit pessimistic locking We already discussed switching all database connections to a higher isolation level than read committed, but our conclusion was that this is a bad default when scalability of the application is a concern. You need better isolation guarantees only for a particular unit of work. Also remember that the persistence context cache provides repeatable reads for entity instances in persistent state. However, this isn t always sufficient. For example, you may need repeatable read for scalar queries: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item i = (Item) session.get(Item.class, 123); String description = (String) session.createQuery(”select i.description from Item i” + ” where i.id = :itemid”) .setParameter(”itemid”, i.getId() ) .uniqueResult(); tx.commit(); session.close(); This unit of work executes two reads. The first retrieves an entity instance by identifier. The second read is a scalar query, loading the description of the already loaded Item instance again. There is a small window in this unit of work in which a concurrently running transaction may commit an updated item description between the two reads. The second read then returns this committed data, and the variable description has a different value than the property i. getDescription().
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.