users@glassfish.java.net

Re: Deisgn pattern question, seed Data initialization ?

From: Bobby Bissett <Robert.Bissett_at_Sun.COM>
Date: Mon, 04 Jan 2010 13:05:32 -0500

On Dec 22, 2009, at 11:28 PM, glassfish_at_javadesktop.org wrote:

> My idea initially was to write a JUnit in which I would create an
> embeddable ejb container and obtain my JpaController beans and use
> the EntityManager to persist initial data though java code.

With v3, you can have a singleton bean that is created on startup and
it can check the DB to see if the data is there. If not, it can insert
it using the code you've already written. It's not the best way to do
it in production since it runs at every startup (and hard-codes the
data), but it's high up on the cool technology factor. Here's a
skeleton of the code that I'm using to do the same thing -- it's
almost too simple to include.

Cheers,
Bobby

------------

//[package]

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//[other imports]

@Singleton
@Startup
public class DataCreatorBean {

     @PersistenceContext(unitName="your_name_here")
     private EntityManager em;

     @PostConstruct
     private void createData() {
         Query query = em.createNamedQuery("...");
         List results = query.getResultList();
         if (results.isEmpty()) {
             // add the data here. you're already in a transaction so
just end with em.persist(something)
         }
     }

}