Example usage for javax.persistence EntityManager isOpen

List of usage examples for javax.persistence EntityManager isOpen

Introduction

In this page you can find the example usage for javax.persistence EntityManager isOpen.

Prototype

public boolean isOpen();

Source Link

Document

Determine whether the entity manager is open.

Usage

From source file:es.us.isa.ideas.utilities.PopulateDatabase.java

public static void main(String[] args) {

    ApplicationContext ctx;/* w w w  .  jav a 2s .  com*/
    EntityManagerFactory emf;
    EntityManager em;
    EntityTransaction et;

    ctx = new ClassPathXmlApplicationContext("utilities/PopulateDatabase.xml");

    emf = Persistence.createEntityManagerFactory("persistenceUnit");
    em = emf.createEntityManager();
    et = em.getTransaction();

    et.begin();
    try {
        for (Entry<String, Object> entry : ctx.getBeansWithAnnotation(Entity.class).entrySet()) {
            em.persist(entry.getValue());
            System.out.println(String.format("Persisting (%s, %s@%d)", entry.getKey(),
                    entry.getValue().getClass().getName(), entry.getValue().hashCode()));
        }
        et.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        et.rollback();
        oops.printStackTrace();
    } finally {
        if (em.isOpen())
            em.close();
        if (emf.isOpen())
            emf.close();
        ((ClassPathXmlApplicationContext) ctx).close();
    }
}

From source file:com.doculibre.constellio.utils.persistence.ConstellioPersistenceContext.java

public static synchronized EntityManager getCurrentEntityManager() {
    init();/*w  w  w.  j  av  a  2  s.c  o m*/
    EntityManager em = ENTITY_MANAGERS.get();
    if (em == null || !em.isOpen()) {
        em = ENTITY_MANAGER_FACTORY.createEntityManager();
        ENTITY_MANAGERS.set(em);
    }
    return em;
}

From source file:org.opentides.dao.impl.AuditLogDaoImpl.java

/**
 * Saves the log event into the database.
 * @param shortMessage//from w w  w.  ja  v a2  s.c om
 * @param message
 * @param entity
 */
public static void logEvent(String message, BaseEntity entity) {
    Long userId = entity.getAuditUserId();
    String username = entity.getAuditUsername();

    if (ApplicationStartupListener.isApplicationStarted()) {
        if (userId == null) {
            _log.error("No userId specified for audit logging on object [" + entity.getClass().getName()
                    + "] for message [" + message + "]. Retrieving user from interceptor.");
            SessionUser user = SecurityUtil.getSessionUser();
            userId = user.getId();
            username = user.getUsername();
        }
    } else {
        userId = new Long(0);
        username = "System Evolve";
    }

    EntityManager em = DatabaseUtil.getEntityManager();
    try {
        em.getTransaction().begin();
        AuditLog record = new AuditLog(message, entity.getId(), entity.getClass(), entity.getReference(),
                userId, username);
        em.persist(record);
        em.flush();
        em.getTransaction().commit();
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:controllers.base.SareTransactionalAction.java

public static <T> T execute(SareTxRunnable<T> action, Context ctx) throws Throwable {
    Validate.notNull(action);//from  www  .ja va 2s.  c om

    T result = null;
    EntityManager em = null;
    try {
        // create entity manager, add it to args, and begin transaction before the call.
        Logger.info(LoggedAction.getLogEntry(ctx, "creating entity manager"));
        em = createEntityManager();
        em.getTransaction().begin();

        // call the actual action.
        result = action.run(em);

        // commit active transaction after the call.
        if (em.isOpen() && em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
    } catch (Throwable e) {
        // rollback on error.
        if (em.isOpen() && em.getTransaction().isActive()) {
            Logger.info(LoggedAction.getLogEntry(ctx, "rolling back transaction"));
            em.getTransaction().rollback();
        }

        // rethrow.
        throw e;
    } finally {
        // close entity manager.
        if (em != null && em.isOpen()) {
            em.close();
        }
    }

    return result;
}

From source file:br.com.i9torpedos.model.service.jpa.EntityManagerUtil.java

public void closeEntityManager(EntityManager em) {

    if (em != null && em.isOpen()) {
        getEntityManager().close();/*from  w  w  w . j  a  v a2 s .  c o m*/
        emf.close();
        log.info("EntityManager fechado com sucesso!!");
    }

}

From source file:com.pocketgorilla.stripesem.TransactionFilter.java

private void doAfter() {
    EntityManager em = provider.getEntityManager(false);
    if ((em != null) && (em.isOpen())) {
        EntityTransaction tx = em.getTransaction();
        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();/*from  w  w  w . j a v  a 2  s . co  m*/
                log.info("Rolled back persistence transaction.");
            } else {
                tx.commit();
                log.debug("Committed persistence transaction.");
            }
        }
        em.close();
        provider.removeEntityManager();
    }
}

From source file:org.spring.data.gemfire.app.dao.vendor.SQLFireJpaUserDao.java

@Override
protected EntityManager prepare(final EntityManager entityManager) {
    Assert.notNull(entityManager, "The JPA EntityManager must not be null!");
    Assert.state(entityManager.isOpen(), "The EntityManager is closed!");

    if (entityManager.getDelegate() instanceof Session) {
        Session session = (Session) entityManager.getDelegate();

        if (session instanceof SessionImpl) {
            try {
                ((SessionImpl) session).connection()
                        .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_NONE);
            } catch (SQLException e) {
                //System.err.printf("Failed to set the JDBC Connection Transaction Isolation Level to (READ_COMMITTED)!%n%1$s%n", e);
                throw new PersistenceException(
                        "Failed to set the JDBC Connection Transaction Isolation-level to (READ_COMMITTED)!",
                        e);/* w  ww  .ja va  2 s .  co  m*/
            }
        }
    }

    return entityManager;
}

From source file:org.drools.container.spring.beans.persistence.DroolsSpringJpaManager.java

public void beginCommandScopedEntityManager() {
    EntityManager cmdScopedEntityManager = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
    if (cmdScopedEntityManager == null || !cmdScopedEntityManager.isOpen()) {
        EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
                .getResource("cmdEM");
        EntityManager em = null;/*w  w w  .  jav  a 2  s  .c  o  m*/
        if (emHolder == null) {
            em = this.emf.createEntityManager();
            emHolder = new EntityManagerHolder(em);
            TransactionSynchronizationManager.bindResource("cmdEM", emHolder);
        } else {
            em = emHolder.getEntityManager();
        }
        this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, em);
    }

    this.getCommandScopedPersistenceContext().joinTransaction();
    this.appScopedEntityManager.joinTransaction();

}

From source file:com.sun.socialsite.business.impl.JPAPersistenceStrategy.java

/**
 * Get the current ThreadLocal EntityManager
 *//*from   w  ww  .  java  2s .c o  m*/
private EntityManager getThreadLocalEntityManager() {
    EntityManager em = threadLocalEntityManager.get();
    if ((em == null) || (!em.isOpen())) {
        em = emf.createEntityManager();
        threadLocalEntityManager.set(em);
    }
    return em;
}

From source file:com.thruzero.domain.jpa.transaction.JpaDatabaseTransactionMgr.java

@Override
public void commitTransaction() {
    if (isTransactionActive()) {
        EntityManager entityManager = doGetCurrentPersistenceManager(false);

        entityManager.getTransaction().commit();

        if (entityManager.isOpen()) {
            entityManager.close();//from   w w  w .  j  a va  2s  . c  o m
        }
    }
}