Accessing a Hibernate Resource
You can access a Hibernate resource from the Hibernate session that is associated with the session factory.
If you create a property named sessionFactory of type Hibernate Resource Template, TIBCO Business Studio adds the following to the abstract implementation class:
import org.osoa.sca.annotations.Property; import com.tibco.amf.sharedresource.runtime.core.hibernate.sharedresource.ProxySessionFactory; private ProxySessionFactory sessionFactory; @Property(name = "sessionFactory") public void setSessionFactory(ProxySessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public ProxySessionFactory getSessionFactory() { return sessionFactory; }
- Procedure
- Retrieve the proxy session factory using the generated getSessionFactory method.
- Register the model class using the session factory addClass method.
- Retrieve the Hibernate session from the session factory using the openSession method.
- Retrieve a transaction from the session.
- Create a query.
- Run the query.
- Save the session.
- Commit the transaction.
- Close the session.
- When the component is destroyed, unregister the model class using the removeClass method.
import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; ... final Session session = getSessionFactory().openSession(); try { /** * Begin a transaction before performing any queries. * Closing the session cleans up the transaction. */ Transaction tx = session.beginTransaction(); final Query query = session.createQuery("UPDATE ..."); ... int result = query.executeUpdate(); if (result == 0) { ... session.save(report); } tx.commit(); } finally { session.close(); } ... @Init public void init() { if (getSessionFactory() == null) { throw new IllegalStateException("Failed to inject ProxySessionFactory"); } /*** Register the ModelClass model class on SessionFactory */ getSessionFactory().addClass(ModelClass.class); try { // Initializes database data. initializeDBData(); } catch (Throwable th) { ... } } ... @Destroy public void destroy() { if (getSessionFactory() != null) { /** * Unregister the ModelClass model class from SessionFactory */ getSessionFactory().removeClass(ModelClass.class); } }