Maven, Hibernate, JPA

9 Comments

I’m a maven noob. Wanted to integrate Hibernate 3 and JPA into a Maven 2 project.  Not really into the hibernate maven plugin (anybody have good/bad experiences with it?) because I’m actually superstitious and like to control things myself, so I decided to integrate manually.  After a little bit of trial and error and updating the JBoss maven repository here’s a sample pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.resteasy</groupId>
    <artifactId>titan-cruise</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>titan-cruise</name>
    <url>http://maven.apache.org</url>
    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.org/maven2</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>hibernate</groupId>
            <artifactId>hibernate3</artifactId>
            <version>3.2.4.SP1</version>
        </dependency>
        <dependency>
            <groupId>hibernate-annotations</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.3.0.GA</version>
        </dependency>
        <dependency>
            <groupId>hibernate-commons-annotations</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>hibernate-entitymanager</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.3.1.GA</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>antlr</groupId>
            <artifactId>antlr</artifactId>
            <version>2.7.7</version>
        </dependency>
        <dependency>
            <groupId>hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>1.8.0.2</version>
        </dependency>
        <dependency>
            <groupId>jboss</groupId>
            <artifactId>jboss-common-core</artifactId>
            <version>2.2.0.GA</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.0.jboss</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.6.0.GA</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

JRuby and ActiveHibernate

1 Comment

No, I’m not changing my mind about Ruby just yet, I’m just building up debate ammo actually. 🙂

Anyways…I’ve been trying to read up on Ruby, Rails, and ActiveRecord lately and came across two different technologies I’d like to ask you readers about. The first is JRuby. JRuby is a Java implementation of Ruby, in the same mold as Jython. It allows you to run Ruby code with the JVM and also gives you the ability to use any Java API you have available in the classpath. The question:

If JRuby is stable, why would you ever want to use vanilla Ruby?

Ruby has traditionally had huge threading problems, from what I’ve read, that Java has pretty much nailed down since it improved its memory model in JDK 5.

The next piece of technology I came across was ActiveHibernate. The idea of this project is to allow Hibernate to generate Ruby rather than Java objects when you interact with your database. The project looks a little raw (there’s no downloads), but if you dive down into the code, you see that the implementation is very small. ActiveHibernate uses Hibernate’s dynamic-map entity mode along with a Ruby specific tuplizer, so there’s only a handul of things to implement. JRuby actually has done most of the work for you by providing nice utility methods to convert Java objects to Ruby. I haven’t tried ActiveHibernate out at all, but what you’d be doing is solely defining hbm.xml mapping files. The Hibernate Tools project allows you to point to a DB and generate hbm.xml files (as well as Java classes and even a small website scaffolding like Rails does), so you’d have the same productivity as active record.

Hibernate has caching (2nd level and query), optimistic locking, a rich query language, and rich mapping strategies. They have also thought about migration strategies as well. So the question is:

If ActiveHibernate is viable why would you ever want to use ActiveRecord?

There are so many great technologies in Java land beyond Hibernate that you are able to leverage with languages that run on top of the JVM. If you believe dynamic un-typesafe languages are the future (i’m not one of them BTW), then don’t you think we should be leveraging all this old technology?

Must I compensate for everything?

16 Comments

I spent a lot of time over the past few months with the JBoss ESB and jBPM teams. It was my first real hands-on experience with the orchestration of both local and remote “web” services. Usually, as a middleware developer you think in terms of milliseconds. How fast can I transmit information from one point to the next and back again? How can I optimize this query to run faster? The jBPM guys think about things very differently. For them, the processes they model could span minutes, hours, days and even weeks or months. Its a very different way of looking at things. For instance, what if you have a process that spans days and something goes wrong? How do you handle failure and abort conditions? You sure as hell can’t do long running activities within a JTA transaction. This would hold up things like database resources too long. No, what you really need is the ability to undo operations in abort situations.

In middleware land, undo is more commonly referred to as Compensating Transactions. What’s an example? Cancellation of an order is a common compensation. When a customer makes an order over the internet, the business process usually goes through a set of committed states before the product is delivered. Let’s take the ordering of a computer for instance:

  • Bill credit card
  • Pull parts from inventory
  • Assemble computer
  • Install software
  • QA
  • Ship

You don’t want to build the computer without billing the customer. Once parts are pulled from inventory, inventory counts must be decremented. No way this can be done in a traditional ACID transaction. Each state transaction must be its own transaction that is committed. If an order is canceled, there are a number of things that must be done. The buyer must have their credit card credited. The computer must also be disassembled and parts sent back to inventory.

Long running conversations aren’t just a property of a business process run inside something like jBPM. Web applications are a perfect example of a long running activity where you don’t want to hold up resources. The Hibernate guys like to handle these situations by holding database updates in memory and flushing them when the activity commits. They suggest the combination of optimistic concurrency and flush mode NEVER/MANUAL to do this. Flush mode NEVER holds all database updates within the Hibernate session until you invoke flush(). Optimistic concurrency ensures you that your database is in the state you want it to be in when you perform the flush. With this approach compensation is not needed at all, because nothing is committed to the database. The problem is that you might have a resource that can’t be managed by Hibernate or that has a high probability of failing optimistic concurrency checks. In that scenario, compensation is the only thing you can do.

So, that’s my explanation of what compensating transactions are. In my next blog I want to talk about how middleware interacts with compensating transactions and whether or not you need a special compensating transaction engine or business activity service to enable compensating transactions.

Co-existence with Hibernate, JPA, and EJB3

15 Comments

How can you slowly migrate existing Hibernate apps to JPA? How can you use Hibernate features and unique mapping capabilities with a JPA deployment? How can you take advantage of EJB3 injection and persistence context management with Hibernate? In this blog I want to show how Hibernate, JPA, and EJB 3.0 can co-exist and compliment one another. This information is fully documented between the Hibernate and JBoss EJB3 projects, but I thought I’d highlight them in this blog to make the community aware that they exist.

Mixing and matching JPA annotations within Hibernate

Using the standard JPA annotations helps out greatly in cutting down the amount of XML metadata you have to type. This annotation metadata is an exact replacement for much of the metadata in hbm.xml. Using them does not require you to use the JPA EntityManager interface. You may still use SessionFactory and Session objects to interact with your database. After downing the Hibernate Anotations project, setting things up is fairly easy:

SessionFactory sessionFactory =
                  new AnnotationConfiguration().buildSessionFactory();

You use hibernate.cfg.xml to specify which exact classes you want mapped by this SessionFactory:

<hibernate-configuration>
 <session-factory>
    <mapping class="com.acme.Flight"/>
    <mapping class="org.jboss.Sky"/>
    <mapping resource="org.acme.orm.xml"/>
 </session-factory>
</hibernate-configuration>

You can mix hbm.xml mapping files with new annotated classes. XML resources can also either be JPA-based XML or Hibernate based. This mixing and matching allows you to quickly prototype new mappings using JPA, but allows these mappings to co-exist with older Hibernate 3 applications.

There are a few more options for configuration. Check out the Hibernate Annotations documentation for more information.

Use Hibernate to configure JPA

If you want to use the JPA Entity Manager API to code a portable application, you may still want to use Hibernate metadata to map your beans. Although the JPA orm mapping is pretty rich, it is still a subset of Hibernate’s functionality. The Hibernate Annotations project provides additional Hibernate-specific annotations to elaborate a persistence mapping where JPA leaves off. If you prefer XML, you can use hbm.xml files to define the mappings for your entity beans. When loading a persistence archive, Hibernate Entity Manager will automatically scan the .jar file for any *hbm.xml files and add them to its mapping information.

Hibernate specific configuration is defined in the properties element of the persistence.xml file. You can configure any hibernate property within this XML blob

<persistence>
 <persistence-unit name="manager1" transaction-type="JTA">
    <jta-data-source>java:/DefaultDS</jta-data-source>
    <properties>
       <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
 </persistence-unit>
</persistence>

You may also define all your hibernate configuration in the usual Hibernate way: within a hibernate.xfg.xml file. You must tell the JPA implementation to use this configuration file through the hibernate.ejb.cfgfile property.

<persistence>
 <persistence-unit name="manager1" transaction-type="JTA">
    <jta-data-source>java:/DefaultDS</jta-data-source>
    <properties>
       <property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
    </properties>
 </persistence-unit>
</persistence>

EJB 3.0 managed persistence sessions

EJB 3.0 has some nice integration with JPA. You can have your EJB session beans manage persistent sessions for you, freeing you from having to create, destroy, and clean up your persistence sessions. It can manage your persistent sessions in two ways:

Transaction-scoped persistence contexts

Transaction-scoped persistence contexts can be injected into your stateful, stateless, or message driven beans. These transaction-scoped contexts only live for the duration of the JTA transaction they are invoked within. When you first interact with an injected transaction-scoped EntityManager within a transaction, an underlying persistence context (in other words, a Hibernate session) is transparently created and associated with the transaction. This associated context is propagated automatically to an nested EJBs that invoke on entity managers of the same persistent unit type. This means that any EJB that invokes on an entity manager will be using the same underlying Hibernate Session.

@Statelesspublic class MyBean implements MyInterface {

 @PersistenceContext(unitName="custDb") EntityManager manager;

...

Extended persistence contexts

In Hibernate terminology, an extended persistence context is one particular Hibernate session. This session may live beyond the duration of a JTA transaction. In EJB 3.0, you can inject an extended persistence context into a stateful session bean. Unlike transaction-scoped entity managers, these persistence contexts are not created and destroyed in a transaction, but instead have their lifecylce tied to that of the SFSB session. This allows you to have conversations with your database that span multiple JTA transactions.

@Statefulpublic class ShoppingCartBean implements ShoppingCart {
{
 @PersistenceContext(unitName="custDb", type=EXTENDED) EntityManager manager;
...
}

Using EJB 3.0 injection annotations with Hibernate

The JBoss EJB 3.0 implementation allows you to use Hibernate Session and SessionFactory as types for targets of the @PersistenceContext and @PersistenceUnit annotations. The injected Session or SessionFactory will behave exactly as if you were instead using the JPA counterparts EntityManager or EntityManagerFactory:

@Statelesspublic class MyBean implements MyInterface
{
 @PersistenceContext(unitName="custDb") org.hibernate.Session session;
 @PersistenceUnit(unitName="custDb") SessionFactory factory;
...
}

Just like with the EJB 3.0/JPA integration, the Hibernate Session will be associated with the JTA transaction and propagated to nested EJB invocations within the same transaction. It is also ok if these nested calls use the EntityManager API instead. The same underlying Hibernate session will still be used for both.

Hiberate Sessions can also represent extended persistence contexts:

@Statefulpublic class ShoppingCartBean implements ShoppingCart
{
 @PersistenceContext(type=EXTENDED) org.hibernate.Session session;
...
}

Again, the EJB container will manage this Hibernate Session the same way it would manage an EntityManager instance.

Obtaining Hibernate objects programmatically

You can always get access to a Hibernate Session object from an EntityManager instance through the standard EntityManager.getDelegate() method. This is a JPA specification feature.

  @PersistenceContext EntityManager manager;
  ...
{      org.hibernate.Session session = (Session)manager.getDelegate();  }

The specification, however, does not provide a way to get at the underlying implementation of a Query. Hibernate should provide most of its extended functionality through JPA query hints. For example, lets say you wanted to enable a query cache:

  javax.persistence.Query query = manager.createQuery(...);
  query.setHint("org.hibernate.cacheable", true);

Conclusion

Hibernate and the JBoss EJB 3.0 project provide multiple ways in which you can mix and match Hibernate and JPA annotations and XML metadata. JBoss EJB 3.0 can manage Hibernate typed objects the same way it can manage JPA objects. Finally the specification provides programmatic ways to get at the underlying Hibernate connection. With the features you should have the flexibility to get at the HIbernate features you need while staying as portable as possible under the JPA specification. Or conversely, you can use well-defined JPA mapping annotations within your Hibernate deployments to make coding simpler and easier.

Disclaimer 😉 This blog was meant to make you aware of certain integration features that exist between JPA, Hibernate, and JBoss EJB 3.0. You should not use it as a reference guide, but rather dive down deeper into each project’s docoumentation. Have fun.

%d bloggers like this: