Opentaps Hibernate Integration
Beginning with opentaps version 1.4, Hibernate will be available as a persistence tool alongside with the original ofbiz entity engine. Hibernate is a more object oriented persistence framework and better suited for the new Domain Driven Architecture, while the ofbiz entity engine will continue to be supported for legacy features from both ofbiz and opentaps. In this document, we will review how the hibernate integration in opentaps works.
Contents
Working with Hibernate in opentaps
Accessing Entities with Hibernate
To use hibernate to access your entities, you will need an org.opentaps.foundation.infrastructure.Session, which is an extension of the org.hibernate.Session class. You can obtain it from the Infrastructure class like this:
session = infrastructure.getSession();
Then, you can work with it as if it were a Hibernate Session:
Transaction tx = session.beginTransaction(); TestEntity newTestEntity = new TestEntity(); newTestEntity.setTestStringField("testInsertTestEntity string field"); newTestEntity.setCreatedStamp(UtilDateTime.nowTimestamp()); session.save(newTestEntity); tx.commit(); session.flush(); // ... TestEntity loadEntity = (TestEntity) session.load(TestEntity.class, newTestEntity.getTestId()); // ... String hql = "from TestEntity eo where eo.testId='" + testEntityId2 + "'"; Query query = session.createQuery(hql); List<TestEntity> list = query.list()
You do not need to close your JDBC connection manually with the opentaps Session, however. When you call
session.close();
It will do it for you automatically.
Under the Hood: How It Works
Base Class Annotations
In opentaps version 1.4, the entity model XML from the ofbiz entity engine is still used as the base definition for all entities. The opentaps POJO generator is used to create base Java objects automatically from these entity definitions. This POJO generator will also create the annotations which hibernate can then use to map those base objects to the database persistence layer. The definitions of the annotations can be found in BaseEntity.ftl file used by the POJO generator.
Generating Hibernate Configuration Files
The POJO Generator will use hot-deploy/opentaps-common/templates/HibernateCfg.ftl to generate a base hibernate configuration file in hot-deploy/opentaps-common/config/hibernate.cfg.xml When opentaps is started, the following new container in framework/base/config/ofbiz-containers.xml
<container name="hibernate-container" class="org.opentaps.common.container.HibernateContainer"> <property name="delegator-name" value="default"/> </container>
will generate all the hibernate configuration XML files in the hot-deploy/opentaps/config/ directory for each data source in your entity engine XML file. For example, it will generate a localmysql.cfg.xml, a localpostgres.cfg.xml
Unit Tests
Unit tests for hibernate are found in org.opentaps.tests.entity.hibernate.HibernateTests in the opentaps-tests component.