Using Hibernate Objects


When the Hibernate archive is deployed, the Hibernate objects are made available to other applications through the provided SessionFactory. There are several ways to use it.

Since the session factory is bound into JNDI, it is possible to simply look it up and manually to create a Hibernate session. The following code does just that:

 InitialContext ctx = new InitialContext(); SessionFactory factory = (SessionFactory)     ctx.lookup("java:/hibernate/CaveatEmptorSessionFactory"); Session hsession = factory.openSession(); 

This requires manual management of the session and the Hibernate transaction, and it may be useful for migrating existing Hibernate code into JBoss. However, in the context of a larger J2EE application, you'll likely want your Hibernate objects to take part in an existing JTA transaction. This would be the normal case if you wanted to access Hibernate objects in a session bean, for example. JBoss provides the org.jboss.hibernate.session. HibernateContext class as the integration piece that does this.

The getSession method returns a Hibernate session that is linked to the current JTA transaction. Naturally, this requires that a JTA transaction exist prior to the call. The following code illustrates the use of getSession:

 Session hsession = HibernateContext.getSession("java:/hibernate/CaveatEmptorSessionFactory"); 

When you get the Hibernate session in this manner, you don't need to close the Hibernate session or manage a Hibernate transaction. You can be sure that all access to the Hibernate session from the current transaction will see the same state, and you can know that your Hibernate access will be committed to the database or rolled back along with the larger JTA transaction.



JBoss 4. 0(c) The Official Guide
JBoss 4.0 - The Official Guide
ISBN: B003D7JU58
EAN: N/A
Year: 2006
Pages: 137

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net