Example usage for javax.persistence EntityManagerFactory createEntityManager

List of usage examples for javax.persistence EntityManagerFactory createEntityManager

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory createEntityManager.

Prototype

public EntityManager createEntityManager();

Source Link

Document

Create a new application-managed EntityManager.

Usage

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * Metodo che restituisce l'oggetto cercato specificando la classe
 * dell'oggetto, la query di ricerca e la mappa dei parametri
 * /*  ww w . j  a  va  2  s .c o m*/
 * @param classObj
 * @param query
 * @param map
 * @return EntityBase
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> T findSingle2(Class<T> classObj, String query, Map<String, Object> map)
        throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Creo la query */
        q = em.createNamedQuery(query);

        /* Verifico che la mappa dei parametri sia valida */
        if (map != null) {

            /* Per ogni oggetto della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        try {
            /* Lancio la query */
            returnValue = (T) q.getSingleResult();
        } catch (NoResultException ex) {
            /* Se non ci son risultati ritorno null */
            returnValue = null;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public void create(EntityBaseStandard entity) throws Exception {
    EntityManagerFactory emf = null;
    // EntityManager em = null;
    boolean tAlreadyActive = false;

    if (entity == null)
        return;// w w  w .  j a  v  a 2s . c  o m

    try {
        if (!passedEm) {
            emf = getEntityManagerFactory();
            em = emf.createEntityManager();
        }

        tAlreadyActive = em.getTransaction().isActive();
        if (!tAlreadyActive) {
            em.getTransaction().begin();
        }

        entity.beforeCreate();
        em.persist(entity);
        entity.afterCreate();

        // Commit only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().commit();
        }

        // if (lazyCloseEM) {
        // em.refresh(entity);
        // }
    } catch (Exception ex) {
        // Rollback only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().rollback();
        }
        ExceptionLogger.logExceptionWithCause(logger, ex);
        throw ex;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
            emf = null;
            em = null;
        }
    }
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public void edit(EntityBaseStandard entity) throws Exception {
    EntityManagerFactory emf = null;
    // EntityManager em = null;
    boolean tAlreadyActive = false;

    if (entity == null)
        return;/*from  w ww  .j  a v a2 s .  co  m*/

    try {
        if (!passedEm) {
            emf = getEntityManagerFactory();
            em = emf.createEntityManager();
        }

        tAlreadyActive = em.getTransaction().isActive();
        if (!tAlreadyActive) {
            em.getTransaction().begin();
        }

        entity.beforeUpdate();
        em.merge(entity);
        entity.afterUpdate();

        // Commit only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().commit();
        }

        // if (lazyCloseEM) {
        // em.refresh(entity);
        // }
    } catch (Exception ex) {
        // Rollback only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().rollback();
        }
        ExceptionLogger.logExceptionWithCause(logger, ex);
        throw ex;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
            emf = null;
            em = null;
        }
    }
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public void editSimple(EntityBaseStandard entity) throws Exception {
    EntityManagerFactory emf = null;
    // EntityManager em = null;
    boolean tAlreadyActive = false;

    if (entity == null)
        return;/*  ww w.  java 2  s  .  c o m*/

    try {
        if (!passedEm) {
            emf = getEntityManagerFactory();
            em = emf.createEntityManager();
        }

        tAlreadyActive = em.getTransaction().isActive();
        if (!tAlreadyActive) {
            em.getTransaction().begin();
        }

        // entity.beforeUpdate();
        em.merge(entity);
        // entity.afterUpdate();

        // Commit only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().commit();
        }

        // if (lazyCloseEM) {
        // em.refresh(entity);
        // }
    } catch (Exception ex) {
        // Rollback only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().rollback();
        }
        ExceptionLogger.logExceptionWithCause(logger, ex);
        throw ex;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
            emf = null;
            em = null;
        }
    }
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * /*from   ww  w .  jav  a  2s.  c o m*/
 * Metodo che restituisce una collezione di oggetti specificati come
 * parametro, tramite la query da lanciare, la mappa dei parametri,
 * l'elemento di inizio e il numero di elementi desiderati (mettendo a 0
 * questo parametro li restituisce tutti)
 * 
 * @param classObj
 * @param query
 * @param map
 * @param firstItem
 * @param batchSize
 * @return
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> List<T> findList2(Class<T> classObj, String query,
        Map<String, Object> map, int firstItem, int batchSize) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Genero la query */
        q = em.createNamedQuery(query);

        /*
         * Se il numero di elementi  diverso da 0 specifico quanti e da
         * dove cominciare
         */
        if (batchSize > 0) {
            q.setFirstResult(firstItem);
            q.setMaxResults(batchSize);
        }

        /* Verifico la validit della mappa */
        if (map != null) {
            /* Per ogni elemento della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }

        /* Calcolo la collezione di elementi desiderati */
        returnValue = (List<T>) q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * //  w  w  w .  j av a2 s. co m
 * Metodo che restituisce una collezione di oggetti specificati come
 * parametro, tramite la query da lanciare, la mappa dei parametri,
 * l'elemento di inizio e il numero di elementi desiderati (mettendo a 0
 * questo parametro li restituisce tutti)
 * 
 * @param classObj
 * @param query
 * @param map
 * @param firstItem
 * @param batchSize
 * @return
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> List<T> findListCustomQuery(Class<T> classObj, String query,
        Map<String, Object> map, int firstItem, int batchSize) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Genero la query */
        q = em.createQuery(query);

        /*
         * Se il numero di elementi  diverso da 0 specifico quanti e da
         * dove cominciare
         */
        if (batchSize > 0) {
            q.setFirstResult(firstItem);
            q.setMaxResults(batchSize);
        }

        /* Verifico la validit della mappa */
        if (map != null) {
            /* Per ogni elemento della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }

        /* Calcolo la collezione di elementi desiderati */
        returnValue = (List<T>) q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public void destroy(EntityBaseStandard entity) throws Exception {
    EntityManagerFactory emf = null;
    // EntityManager em = null;
    boolean tAlreadyActive = false;

    if (entity == null)
        return;/*from   w w  w . ja  v  a 2  s . c o m*/

    try {
        if (!passedEm) {
            emf = getEntityManagerFactory();
            em = emf.createEntityManager();
        }

        tAlreadyActive = em.getTransaction().isActive();
        if (!tAlreadyActive) {
            em.getTransaction().begin();
        }

        // entity = find(entity.getClass(), entity.getId());

        // if (entity != null) {
        entity.beforeDelete();
        em.remove(entity);
        entity.afterDelete();
        // } else {
        // throw new
        // Exception("Impossibile trovare la Entit da Cancellare");
        // }

        // Commit only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().commit();
        }
    } catch (Exception ex) {
        // Rollback only if local transaction
        if (!tAlreadyActive && (em != null) && (em.getTransaction().isActive())) {
            em.getTransaction().rollback();
        }
        // logger.error("Errore su destroy di controller : " +
        // ex.getMessage());
        ExceptionLogger.logExceptionWithCause(logger, ex);

        throw ex;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
            emf = null;
            em = null;
        }
    }
}

From source file:org.compass.gps.device.jpa.embedded.eclipselink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded EclipseLink support enabled, initializing for session [" + session + "]");
    }//from   ww w.  j  av  a  2  s  .  co m
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> eclipselinkProps = new HashMap();
    eclipselinkProps.putAll(persistenceUnitInfo.getProperties());
    eclipselinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) eclipselinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : eclipselinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean eclipselinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            eclipselinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            eclipselinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with EclipseLink transaction listeners
        eclipselinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using EclipseLink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    EclipseLinkJpaEntityLifecycleInjector lifecycleInjector = new EclipseLinkJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EclipseLinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since EclipseLink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, eclipselinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded EclipseLink support active");
    }
}

From source file:org.compass.gps.device.jpa.embedded.toplink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded TopLink Essentials support enabled, initializing for session [" + session
                + "]");
    }//  w  ww .  ja v a2 s.  c o  m
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> toplinkProps = new HashMap();
    toplinkProps.putAll(persistenceUnitInfo.getProperties());
    toplinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) toplinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : toplinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean toplinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            toplinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            toplinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with Toplink transaction listeners
        toplinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using Toplink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    TopLinkEssentialsJpaEntityLifecycleInjector lifecycleInjector = new TopLinkEssentialsJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EmbeddedToplinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since Toplink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, toplinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded TopLink Essentials support active");
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

private EntityManagerFactory createFactory() {
    jqmlogger.debug("Creating connection pool to database");

    InputStream fis = null;/*from w  ww .j av  a2  s. c  o m*/
    try {
        fis = this.getClass().getClassLoader().getResourceAsStream("META-INF/jqm.properties");
        if (fis == null) {
            jqmlogger.trace("No jqm.properties file found.");
        } else {
            p.load(fis);
            jqmlogger.trace("A jqm.properties file was found");
        }
    } catch (IOException e) {
        // We allow no configuration files, but not an unreadable configuration file.
        throw new JqmClientException("META-INF/jqm.properties file is invalid", e);
    } finally {
        closeQuietly(fis);
    }

    EntityManagerFactory newEmf = null;
    if (p.containsKey("javax.persistence.nonJtaDataSource")) {
        // This is a hack. Some containers will use root context as default for JNDI (WebSphere, Glassfish...), other will use
        // java:/comp/env/ (Tomcat...). So if we actually know the required alias, we try both, and the user only has to provide a
        // root JNDI alias that will work in both cases.
        try {
            newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
            // Do a stupid query to force EMF initialization
            EntityManager em = newEmf.createEntityManager();
            em.createQuery("SELECT n from Node n WHERE 1=0").getResultList().size();
            em.close();
        } catch (RuntimeException e) {
            if (e.getCause() != null && e.getCause().getCause() != null
                    && e.getCause().getCause() instanceof NameNotFoundException) {
                jqmlogger.debug("JNDI alias " + p.getProperty("javax.persistence.nonJtaDataSource")
                        + " was not found. Trying with java:/comp/env/ prefix");
                p.setProperty("javax.persistence.nonJtaDataSource",
                        "java:/comp/env/" + p.getProperty("javax.persistence.nonJtaDataSource"));
                newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
                // Do a stupid query to force EMF initialization
                EntityManager em = newEmf.createEntityManager();
                em.createQuery("SELECT n from Node n WHERE 1=3").getResultList().size();
                em.close();
            } else {
                throw e;
            }
        }
    } else {
        newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
    }
    return newEmf;
}