Thursday, January 05, 2006

Using Glassfish EJB 3.0 Persistence in J2SE

UPDATED 7th May 2006
One of the great things about EJB 3.0 is its support for persistence in J2SE environments. This is great for trying out various persistence features without the overhead of developing an application which must be deployed to an application server before it can be tested.

To use EJB persistence in your J2SE program, you need a couple of jar files that come with Glassfish distribution. These are:

  1. /glassfish/lib/toplink-essentials.jar
  2. /glassfish/lib/toplink-essentials-agent.jar

These jar files are available as a separate standlone bundle here.

You require the toplink-essentials.jar during development. At runtime, you need to add the following option to your Java command line:

-javaagent:/glassfish/lib/toplink-essentials-agent.jar

This will automatically include the toplink-essentials.jar to your classpath.

There is another preliminary step that you need to be aware of. You need to create a file named persistence.xml in a directory called META-INF. This directory must be in your classpath. Given below is an example of a persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="em1" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<class>entity.Table</class>
<properties>
<property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:sample" />
<property name="toplink.jdbc.user" value="scott" />
<property name="toplink.jdbc.password" value="tiger" />
<property name="toplink.logging.level" value="INFO" />
</properties>
</persistence-unit>
</persistence>
If you use set logging level to FINEST you can see the SQLs being generated by Toplink.

To access the EJB 3.0 EntityManager in your program, add lines similar to following:

  EntityManager em = Persistence.createEntityManagerFactory("em1")
.createEntityManager();

2 comments:

Dibyendu Majumdar said...

Thanks for pointing out - its corrected now.

Unknown said...

If there are a lot of entities , how do you specify them. When I tried specifying a jar file, it was unable to pick up the entities, so do I have to specify each one of them using the class tag or is there any other way of doing it.