Example usage for org.hibernate.ejb HibernateEntityManager getSession

List of usage examples for org.hibernate.ejb HibernateEntityManager getSession

Introduction

In this page you can find the example usage for org.hibernate.ejb HibernateEntityManager getSession.

Prototype

Session getSession();

Source Link

Document

Retrieve a reference to the Hibernate org.hibernate.Session used by this javax.persistence.EntityManager .

Usage

From source file:com.javaetmoi.core.persistence.hibernate.JpaLazyLoadingUtil.java

License:Apache License

/**
 * Populate a lazy-initialized object graph by recursivity.
 * //from   w  ww  .ja  v  a 2s  . c  om
 * <p>
 * This method deeply navigates into a graph of entities in order to resolve uninitialized
 * Hibernate proxies.<br>
 * The goal is to avoid any {@link lazyinitializationexception} once entities are detached from
 * the Hibernate session.<br>
 * May attention: this method has to be called from an open persistent context / Hibernate
 * session.
 * </p>
 * 
 * @param currentEntityManager
 *            current JPA entity manager still open
 * @param entities
 *            a {@link Collection} of Hibernate entities to load
 * @return the {@link Collection} of Hibernate entities fully loaded. Similar to the entities
 *         input parameter. Usefull when calling this method in a return statement.
 * 
 */
public static <E> Collection<E> deepHydrate(final EntityManager currentEntityManager, Collection<E> entities) {
    if (currentEntityManager instanceof HibernateEntityManager) {
        HibernateEntityManager entityManager = (HibernateEntityManager) currentEntityManager;
        return LazyLoadingUtil.deepHydrate(entityManager.getSession(), entities);
    }
    throw new RuntimeException("Only the Hibername implementation of JPA is currently supported");
}

From source file:com.javaetmoi.core.persistence.hibernate.JpaLazyLoadingUtil.java

License:Apache License

/**
 * Populate a lazy-initialized object graph by recursivity.
 * /*from  w  w  w.j  ava 2s  . c  o m*/
 * <p>
 * This method deeply navigates into a graph of entities in order to resolve uninitialized
 * Hibernate proxies.<br>
 * The goal is to avoid any {@link lazyinitializationexception} once entities are detached from
 * the Hibernate session.<br>
 * May attention: this method has to be called from an open persistent context / Hibernate
 * session.
 * </p>
 * 
 * @param currentEntityManager
 *            current JPA entity manager still open
 * @param entity
 *            a single Hibernate entity or a simple java class referencing entities
 * @return the Hibernate entity fully loaded. Similar to the entity input parameter. Usefull
 *         when calling this method in a return statement.
 * 
 */
public static <E> E deepHydrate(final EntityManager currentEntityManager, E entity) {
    if (currentEntityManager instanceof HibernateEntityManager) {
        HibernateEntityManager entityManager = (HibernateEntityManager) currentEntityManager;
        return LazyLoadingUtil.deepHydrate(entityManager.getSession(), entity);
    }
    throw new RuntimeException("Only the Hibername implementation of JPA is currently supported");
}

From source file:com.locke.library.persistence.dao.jpa.AbstractJpaDao.java

License:Apache License

/**
 * {@inheritDoc}/*ww w .j a v  a 2s . com*/
 */
public void lock(final T object, final LockType lockType) {
    if (lockType == LockType.READ) {
        getEntityManager().lock(object, LockModeType.READ);
    } else if (lockType == LockType.WRITE) {
        getEntityManager().lock(object, LockModeType.WRITE);
    } else if (lockType == LockType.ATTACH) {
        final HibernateEntityManager manager = (HibernateEntityManager) getEntityManager();
        manager.getSession().lock(object, LockMode.NONE);
    } else {
        throw new UnsupportedOperationException("Unsupported lock type " + lockType);
    }
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelTrainerTask.java

License:Apache License

@Override
public void train(Model model) {
    final int lookahead = model.getLookahead();
    final TimeUnits timeUnits = model.getTimeUnits();
    final long durationOfUnit = timeUnits.getDuration();

    final Date startDate = TimeUnits.floor(model.getStartDate(), timeUnits);
    final Date endDate = TimeUnits.ceil(model.getEndDate(), timeUnits);

    final Timestamp startDatePoints = new Timestamp(startDate.getTime() - durationOfUnit);
    final Timestamp endDatePoints = new Timestamp(endDate.getTime() + (lookahead * durationOfUnit));

    List<DataSetPoint> points = this.dataSetPointDao.findAndAggregatePointsGroupedByUnit(
            model.getTrainingDataSet(), startDatePoints, endDatePoints, timeUnits);
    Map<Date, DataSetPoint> pointMap = toMap(points);

    final Map<Date, Float> percentChangeMap = calculatePercentChange(points, pointMap);

    // should release these collections once percent change is calculated
    points = null;/*w  w w  . j  av  a2s  .  c o m*/
    pointMap = null;

    final HibernateEntityManager hem = this.em.unwrap(HibernateEntityManager.class);
    final Session session = hem.getSession();

    final Long userId = model.getUserId();
    final DocumentState state = null;
    final String queryString = model.getTopic().getSearchExpression();
    final ScrollableResults scrollableResults = this.documentDao.scrollableSearch(userId, state, queryString,
            SortOrder.DATE_ASC, startDatePoints, endDatePoints);

    try {
        final EventStream eventStream = new DocumentScoreEventStream(model, scrollableResults, session,
                percentChangeMap);
        final DataIndexer dataIndexer = new TwoPassDataIndexer(eventStream, this.cutoff);

        if (!logger.isDebugEnabled()) {
            GIS.PRINT_MESSAGES = false;
        }

        logger.debug("Invoking GIS.trainModel");
        final GISModel gisModel = GIS.trainModel(this.iterations, dataIndexer);
        logger.debug("GIS.trainModel complete");

        // because we've been clearing the entity manager's session
        model = this.modelDao.get(model.getId());
        writeModelToFile(model, gisModel);
        logger.info("Created model: " + gisModel);
        model.onTrainingComplete();

    } catch (final OutOfMemoryError e) {
        logError(model.getId(), e);
        throw e;
    } catch (final Exception e) {
        logError(model.getId(), e);
    } finally {
        scrollableResults.close();
    }
}

From source file:com.tesora.dve.common.catalog.DAOPersistProvider.java

License:Open Source License

public DAOPersistProvider(CatalogDAO dao) throws PEException {
    EntityManager em = dao.getEntityManager();
    HibernateEntityManager hem = (HibernateEntityManager) em;
    session = hem.getSession();
}

From source file:it.eng.qbe.statement.jpa.JPQL2SQLStatementRewriter.java

License:Mozilla Public License

/**
 * Rewrite the JPQL query in a SQL String (The persistence provider implementation in use is Hibernate) 
 * @param query The JPQL query/*from   ww  w .j  av a 2  s .  co  m*/
 * @return the string of the JPQL query translated in SQL
 */
private String rewriteHibernate(Query query) {
    org.hibernate.ejb.HibernateEntityManager em = (org.hibernate.ejb.HibernateEntityManager) this.entityManager;
    org.hibernate.ejb.HibernateQuery qi = (org.hibernate.ejb.HibernateQuery) (query);
    em.getSession();
    HQL2SQLStatementRewriter queryRewriter = new HQL2SQLStatementRewriter(em.getSession());
    String sqlQueryString = queryRewriter.rewrite(qi.getHibernateQuery().getQueryString());
    return sqlQueryString;
}

From source file:org.activityinfo.fixtures.MockHibernateModule.java

License:Open Source License

@Provides
public Session provideHibernateSession(EntityManager em) {
    HibernateEntityManager hem = (HibernateEntityManager) em;
    return hem.getSession();
}

From source file:org.activityinfo.server.database.hibernate.HibernateModule.java

License:Open Source License

@Provides
public Session provideSession(EntityManager em) {
    HibernateEntityManager hem = (HibernateEntityManager) em;
    return hem.getSession();
}

From source file:org.activityinfo.server.database.hibernate.SchemaServlet.java

License:Open Source License

public static void performMigration(HibernateEntityManager entityManager) {
    entityManager.getSession().doWork(new Work() {

        @Override/*from  w  ww. j  a  va2 s. co m*/
        public void execute(Connection connection) throws SQLException {

            Liquibase liquibase;
            try {
                liquibase = new Liquibase("org/activityinfo/database/changelog/db.changelog-master.xml",
                        new ClassLoaderResourceAccessor(), new CloudSqlConnection(connection));
                liquibase.update(null);
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Exception whilst migrating schema", e);
            }
        }
    });
}

From source file:org.activityinfo.server.endpoint.gwtrpc.AdvisoryLock.java

License:Open Source License

public AdvisoryLock(HibernateEntityManager entityManager) {
    Preconditions.checkNotNull(entityManager);

    this.entityManager = entityManager;

    try {/*from www  .  ja  v  a2  s. c o  m*/
        Stopwatch stopwatch = Stopwatch.createStarted();

        String sql = String.format("SELECT GET_LOCK('%s', %s)", ADVISORY_LOCK_NAME, ADVISORY_GET_LOCK_TIMEOUT);

        Query query = entityManager.getSession().createSQLQuery(sql);
        Object result = query.uniqueResult();

        if (result == null) {
            throw new UnexpectedCommandException("Error occurred while trying to obtain advisory lock.");
        }

        int resultCode = ((Number) result).intValue();
        if (resultCode == TIMEOUT_CODE) { // time out
            LOGGER.severe("Timed out waiting for write lock.");
            throw new CommandTimeoutException();
        }

        if (resultCode != SUCCESS_CODE) { // not success
            LOGGER.severe("Failed to acquire lock, result code: " + resultCode);
            throw new RuntimeException("Failed to acquire lock, result code: " + resultCode);
        }

        stopwatch.stop();
        LOGGER.finest("Acquiring advisory lock takes: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    } catch (CommandTimeoutException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Internal error during acquiring advisory lock: " + e.getMessage(), e);
        throw new RuntimeException("Exception caught while trying to acquire update lock", e);
    }
}