Thursday, January 10, 2008

Using JPA to bind Entity Beans to a Database

Here's a quick step thru of how to use JPA to bind an entity bean to a database table. This example uses Glassfish v2. It is amazing at how simple persisting entity beans has become with both EJB 3.0/JPA.

1.) Create Entity Beans.
2.) Configure the persistence unit. I created a persistence.xml file for Glassfish with the following contents...

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
<persistence-unit name="ReviewModulePU" transaction-type="JTA">

Each class signifies 1 of several entity beans.

3.) Add the following code to persist the data objects as they are defined...

EntityManagerFactory emf;

EntityManager em;

String PERSISTENCE_UNIT_NAME = "ReviewModulePU";

emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

em = emf.createEntityManager();



// org is an entity bean that is being persisted to the db



} finally {




This is an oversimplified example. It does by no means manage retrieving data objects or attempt to abstract the entity beans in any controlled manner. It is just the quick and ugly version for future reference.

No comments: