Monday, August 08, 2005

EJB3 EntityManager

Since my first post about Entity EJBs with Hibernate, the Hibernate team put out a new beta implementation of javax.persistence.EntityManager. So I wondered what exactly it would take to jettison all the hibernate imports from my class. Well it turned out to be pretty simple. First I substituted the hibernate.cfg.xml file for a META-INF/persistence.xml file that looks like this:

<entity-manager>
<name>manager1</name>
<properties>
<property
name="hibernate.connection.driver_class"
value="org.postgresql.Driver"/>
<property
name="hibernate.connection.url"
value="jdbc:postgresql://127.0.0.1:5432/myDatabase"/>
<property
name="hibernate.connection.username"
value="darcy"/>
<property
name="hibernate.connection.password"
value="darcy"/>
<property
name="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
</entity-manager>

The interesting thing about this is that it autodiscovers the annotated classes. No longer do I have to individually list each persistent class. Secondly, I changed my main method to look like this:

public static void main(String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("manager1");

EntityManager em = emf.createEntityManager();
try{
Brand b = (Brand)em.createQuery("select b from Brand as b")
.setMaxResults(1)
.getSingleResult();
System.out.println(b.getName());
}finally{
em.close();
}
}

You can see that this code is very similar to the Hibernate code that I posted earlier. Obviously the class names and some of the methods are different (like getSingleResult() instead of uniqueResult()) but at first glance it looks like getting started is pretty easy. It'll be interesting to see some of the differences between Session and EntityManager.

No comments: