Tuesday, September 6, 2011

Accessing database during application initialization

In development state most applications need dummy data which should be imported on application initialization. During this phase Seam's TransactionManager is not initialized yet. This means we have to build our UserTransaction manually:

@PersistenceContext
private EntityManager em;

@Inject
private UserTransaction utx;

public void importData(@Observes @Initialized WebApplication webapp) {
    try {
        utx.begin();
        em.persist(new MyDatabaseEntity());
        utx.commit();
    } catch (Exception e) {
        log.error("Import failed. Seed data will not be available.", e);
        try {
            if (utx.getStatus() == Status.STATUS_ACTIVE) {
                try {
                    utx.rollback();
                } catch (Exception rbe) {
                    log.error("Error rolling back transaction", rbe);
                }
            }
        } catch (Exception se) {
        }
    }
}

No comments:

Post a Comment