Example usage for org.hibernate Session getSessionFactory

List of usage examples for org.hibernate Session getSessionFactory

Introduction

In this page you can find the example usage for org.hibernate Session getSessionFactory.

Prototype

SessionFactory getSessionFactory();

Source Link

Document

Get the session factory which created this session.

Usage

From source file:org.jboss.pnc.datastore.repositories.DefaultSequenceHandlerRepository.java

License:Open Source License

@Override
public void dropSequence(final String sequenceName) {

    Work work = new Work() {
        @Override//from  ww  w. j av a  2  s  .c o  m
        public void execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection
                        .prepareStatement(dialect.getDropSequenceStrings(sequenceName)[0]);
                preparedStatement.execute();
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    sessionFactory.getCurrentSession().doWork(work);
}

From source file:org.jboss.pnc.datastore.repositories.SequenceHandlerRepository.java

License:Open Source License

public Long getNextID(final String sequenceName) {

    ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
        @Override//from w  w  w .  j a  va2 s  . c  o  m
        public Long execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getSequenceNextValString(sequenceName));
                resultSet = preparedStatement.executeQuery();
                resultSet.next();
                return resultSet.getLong(1);
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();

    Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
    return maxRecord;
}

From source file:org.jboss.pnc.datastore.repositories.SequenceHandlerRepository.java

License:Open Source License

public void createSequence(final String sequenceName) {

    if (sequenceExists(sequenceName)) {
        return;/*w ww . j  av a2s  . c  o m*/
    }
    Work work = new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection
                        .prepareStatement(dialect.getCreateSequenceStrings(sequenceName, 1, 1)[0]);
                preparedStatement.execute();
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    sessionFactory.getCurrentSession().doWork(work);
}

From source file:org.jboss.pnc.datastore.repositories.SequenceHandlerRepository.java

License:Open Source License

public boolean sequenceExists(final String sequenceName) {
    ReturningWork<Boolean> work = new ReturningWork<Boolean>() {
        @Override//from w  w  w .ja  va  2 s.  c  o  m
        public Boolean execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getQuerySequencesString());
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    if (sequenceName.equals(resultSet.getString(1))) {
                        return true;
                    }
                }
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }
            return false;

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    return sessionFactory.getCurrentSession().doReturningWork(work);
}

From source file:org.jboss.pnc.datastore.repositories.SequenceHandlerRepository.java

License:Open Source License

public void dropSequence(final String sequenceName) {

    Work work = new Work() {
        @Override/*www .j  a  v a  2s. co m*/
        public void execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection
                        .prepareStatement(dialect.getDropSequenceStrings(sequenceName)[0]);
                preparedStatement.execute();
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    sessionFactory.getCurrentSession().doWork(work);
}

From source file:org.jboss.seam.wiki.core.nestedset.listener.NestedSetOperation.java

License:LGPL

protected Connection getConnection(Session session) throws Exception {
    // We do not use session.connection() because it conflicts with Hibernates aggressive collection release
    return ((SessionFactoryImpl) session.getSessionFactory()).getConnectionProvider().getConnection();
}

From source file:org.jboss.tools.hibernate3_5.console.ConsoleExtension3_5.java

License:Open Source License

private boolean hasMetaData(Object object, Session currentSession) {
    return currentSession.getSessionFactory()
            .getClassMetadata(HibernateProxyHelper.getClassWithoutInitializingProxy(object)) != null;
}

From source file:org.jboss.tools.hibernate3_5.console.EntityPropertySource.java

License:Open Source License

public EntityPropertySource(final Object object, final Session currentSession, HibernateExtension extension) {
    this.currentSession = currentSession;
    this.extension = extension;
    reflectedObject = object;/*  w  w  w .  ja v  a2  s  .  c om*/
    if (currentSession.isOpen()) {
        classMetadata = currentSession.getSessionFactory()
                .getClassMetadata(currentSession.getEntityName(reflectedObject));
    } else {
        classMetadata = currentSession.getSessionFactory()
                .getClassMetadata(HibernateProxyHelper.getClassWithoutInitializingProxy(reflectedObject));
    }

}

From source file:org.medici.bia.dao.document.DocumentDAOJpaImpl.java

License:Open Source License

/**
 * //from w  w w  .ja v  a 2 s  .com
 * @throws PersistenceException
 */
public void generateIndex() throws PersistenceException {
    Session session = null;
    FullTextSession fullTextSession = null;
    ScrollableResults results = null;
    try {
        EntityManager entityManager = getEntityManager();
        session = ((HibernateEntityManager) entityManager).getSession();
        session = session.getSessionFactory().openSession();
        fullTextSession = org.hibernate.search.Search.getFullTextSession(session);

        Long total = (Long) entityManager.createQuery("SELECT count(entryId) FROM Document").getSingleResult();
        logger.info("Total Entities to be indexed : " + total);

        if (total > 0) {
            Transaction tx = fullTextSession.beginTransaction();
            fullTextSession.purgeAll(Document.class);
            tx.commit();
            logger.info("Removed all documents.");
            Integer numberOfElements = 100;

            Integer numberOfElementsBeforeGC = 1000;
            String queryJPA = "FROM Document ORDER BY entryId asc";

            org.hibernate.Query query = session.createQuery(queryJPA);
            tx = fullTextSession.beginTransaction();
            query.setReadOnly(true);
            query.setLockMode("a", LockMode.NONE);
            results = query.scroll(ScrollMode.FORWARD_ONLY);
            Integer resultNumber = 0;
            while (results.next()) {
                Document document = (Document) results.get(0);
                fullTextSession.index(document);
                resultNumber++;

                if (resultNumber % numberOfElements == 0) {
                    logger.info("Initiating Lucene Index Flush... ");
                    fullTextSession.flushToIndexes();
                    fullTextSession.clear();
                    logger.info("Finished the Lucene Index Flush...  Total records on index " + resultNumber
                            + "/" + total);
                }

                if (resultNumber % numberOfElementsBeforeGC == 0) {
                    System.gc();
                    logger.info("Invoked Garbage collector to prevent OutOfMemory Errors");
                }
            }

            fullTextSession.flushToIndexes();
            fullTextSession.clear();
            tx.commit();

            logger.info("Initiating Lucene Index Optimze...");
            SearchFactory searchFactory = fullTextSession.getSearchFactory();
            searchFactory.optimize(Document.class);
            logger.info("Finished Lucene Index Optimze");
        } else {
            logger.info("No Entities found to be indexed.");
        }
        logger.info("Indexing documents terminated without errors.");
    } catch (Throwable throwable) {
        logger.error(throwable);
    } finally {
        if (results != null) {
            results.close();
        }
        if (fullTextSession != null) {
            fullTextSession.close();
        }
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.medici.bia.dao.document.DocumentDAOJpaImpl.java

License:Open Source License

/**
 * //from   w  w  w .  j a v a  2s  .com
 * @throws PersistenceException
 */
@Override
public void updateIndex(Date fromDate) throws PersistenceException {
    Session session = null;
    FullTextSession fullTextSession = null;
    ScrollableResults results = null;
    try {
        EntityManager entityManager = getEntityManager();
        session = ((HibernateEntityManager) entityManager).getSession();
        session = session.getSessionFactory().openSession();
        fullTextSession = org.hibernate.search.Search.getFullTextSession(session);

        Query queryTotal = entityManager
                .createQuery("SELECT count(entryId) FROM Document where lastUpdate>=:lastUpdate");
        queryTotal.setParameter("lastUpdate", fromDate);
        Long total = (Long) queryTotal.getSingleResult();
        logger.info("Total Entities to be updated : " + total);

        if (total > 0) {
            Integer numberOfElements = 50;
            Integer numberOfElementsBeforeGC = 1000;
            org.hibernate.Query query = session.createQuery("FROM Document where lastUpdate>=:lastUpdate");
            query.setParameter("lastUpdate", fromDate);

            Transaction tx = fullTextSession.beginTransaction();
            query.setReadOnly(true);
            query.setLockMode("a", LockMode.NONE);
            results = query.scroll(ScrollMode.FORWARD_ONLY);
            Integer resultNumber = 0;
            while (results.next()) {
                Document document = (Document) results.get(0);
                fullTextSession.delete(document);
                fullTextSession.index(document);
                resultNumber++;

                if (resultNumber % numberOfElements == 0) {
                    flushingFullTextSession(total, resultNumber, fullTextSession);
                }

                if (resultNumber % numberOfElementsBeforeGC == 0) {
                    System.gc();
                    logger.info("Invoked Garbage collector to prevent OutOfMemory Errors");
                }
            }

            flushingFullTextSession(total, resultNumber, fullTextSession);

            /*            logger.info("Initiating Lucene Index Optimze...");
                          SearchFactory searchFactory = fullTextSession.getSearchFactory();
                          searchFactory.optimize(Document.class);
            */
            logger.info("Finished Lucene Index Optimze");

            tx.commit();
        } else {
            logger.info("No Entities found to be indexed.");
        }
        logger.info("Indexing documents terminated without errors.");
    } catch (Throwable throwable) {
        logger.error(throwable);
    } finally {
        if (results != null) {
            results.close();
        }
        /*if (fullTextSession.isOpen()) {
           fullTextSession.close();
        }*/
        if (session.isOpen()) {
            session.close();
        }
    }
}