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="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ReviewModulePU" transaction-type="JTA">
<jta-data-source>review</jta-data-source>
<class>reviewmodule.entity.Category</class>
<class>reviewmodule.entity.Company</class>
<class>reviewmodule.entity.Product</class>
<class>reviewmodule.entity.Review</class>
<class>reviewmodule.entity.User</class>
<class>reviewmodule.entity.WatchList</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>


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();


em.getTransaction().begin();

try{

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

em.persist(org);

em.getTransaction().commit();

} finally {

em.close();

emf.close();

}

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: