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

  1. Retrieve the proxy session factory using the generated getSessionFactory method.
  2. Register the model class using the session factory addClass method.
  3. Retrieve the Hibernate session from the session factory using the openSession method.
  4. Retrieve a transaction from the session.
  5. Create a query.
  6. Execute the query.
  7. Save the session.
  8. Commit the transaction.
  9. Close the session.
  10. When the component is destroyed, unregister the model class using the removeClass method.

Example

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);
	}
	}