Example usage for org.hibernate SessionFactory getCurrentSession

List of usage examples for org.hibernate SessionFactory getCurrentSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getCurrentSession.

Prototype

Session getCurrentSession() throws HibernateException;

Source Link

Document

Obtains the current session.

Usage

From source file:org.geolatte.common.automapper.AutoMapperTest.java

License:Open Source License

private void doWithinTransaction(final SessionFactory sf, TxOp op) throws Exception {
    Transaction tx = null;// w  w  w.j a v  a 2  s .co  m
    try {
        tx = sf.getCurrentSession().beginTransaction();
        op.execute(sf.getCurrentSession());
        tx.commit();
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
        if (tx != null)
            tx.rollback();
        throw e;
    }
}

From source file:org.geolatte.featureserver.dbase.StandardFeatureReader.java

License:Open Source License

private void beginTransaction(SessionFactory factory) {
    trans = factory.getCurrentSession().beginTransaction();
}

From source file:org.geolatte.featureserver.dbase.StandardFeatureReader.java

License:Open Source License

private Criteria toExecutableCriteria(SessionFactory factory, Class entityClass, DetachedCriteria detCrit) {
    if (detCrit == null) {
        return factory.getCurrentSession().createCriteria(entityClass);
    } else {//from w w w.j a  v a2 s .  c o  m
        return detCrit.getExecutableCriteria(factory.getCurrentSession());
    }
}

From source file:org.geoserver.hibernate.HibUtil.java

License:Open Source License

public static void tearDownSession(SessionFactory sessionFactory, Throwable error) {
    Session session = sessionFactory.getCurrentSession();

    if (session.isOpen()) {
        session.close();// ww w.j  a v a  2 s  .c  o m
    }

    TransactionSynchronizationManager.unbindResource(sessionFactory);
    TransactionSynchronizationManager.clearSynchronization();
}

From source file:org.glite.security.voms.admin.integration.orgdb.OrgDBMembershipSynchronizationTask.java

License:Apache License

public void run() {

    SessionFactory sf = OrgDBSessionFactory.getSessionFactory();

    long startTime = System.currentTimeMillis();

    try {//from  ww w. j  av a2 s. c  o m

        if (sf.openSession() == null) {
            throw new OrgDBError("Error opening session to OrgDB");
        }

        sf.getCurrentSession().beginTransaction();

        ScrollableResults allUserCursor = VOMSUserDAO.instance().findAllWithCursor();

        int updateCount = 0;

        while (allUserCursor.next()) {

            OrgDBVOMSPersonDAO dao = OrgDBDAOFactory.instance().getVOMSPersonDAO();

            VOMSUser u = (VOMSUser) allUserCursor.get(0);

            VOMSOrgDBPerson orgDbPerson = lookupOrgDBPerson(u, sf.getCurrentSession());

            if (orgDbPerson != null) {
                updateCount++;

                Participation validParticipation = dao.findValidParticipationInExperiment(orgDbPerson,
                        experimentName);

                synchronizationStrategy.synchronizeMemberInformation(u, orgDbPerson, experimentName,
                        validParticipation);

                if (validParticipation == null) {
                    expiredParticipationStrategy.handleOrgDbExpiredParticipation(u, orgDbPerson,
                            experimentName);
                }

                // Flush some updates out and release memory

                if (updateCount % UPDATE_COUNT_BATCH == 0) {

                    log.debug("Flushing session after {} updates.", updateCount);

                    sf.getCurrentSession().flush();
                    sf.getCurrentSession().clear();
                }

            } else {

                log.warn("No OrgDB record found for user {}.", u);
                missingMembershipStrategy.handleMissingMembershipRecord(u);
            }

        }

        sf.getCurrentSession().getTransaction().commit();

    } catch (OrgDBError e) {

        log.error("OrgDB exception caught: {}", e.getMessage());

        if (log.isDebugEnabled()) {
            log.error("OrgDB exception caught: {}", e.getMessage(), e);
        }

        try {

            sf.getCurrentSession().getTransaction().rollback();

        } catch (Throwable t) {
            log.error("Error rolling back OrgDB transaction: {}", t.getMessage(), t);
        }

    } finally {

        sf.getCurrentSession().close();

        long elapsedTime = System.currentTimeMillis() - startTime;
        log.info("OrgDB synchronization took {} seconds.", TimeUnit.MILLISECONDS.toSeconds(elapsedTime));

    }

}

From source file:org.glite.security.voms.admin.integration.orgdb.servlet.OrgDbHibernateSessionFilter.java

License:Apache License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    chain.doFilter(request, response);//from  w  ww . j  ava2  s .  co  m

    SessionFactory sf = OrgDBSessionFactory.getSessionFactory();

    try {

        if (sf == null) {
            throw new VOMSFatalException("OrgDBSessionFactory not initialized!");
        }

        if (sf.getCurrentSession() == null) {
            LOG.debug("No session opened with CERN HR db.");
            return;
        }

        if (sf.getCurrentSession().getTransaction() == null) {
            LOG.debug("No transaction opened with CERN HR db.");
            return;
        }

        if (!sf.getCurrentSession().getTransaction().isActive()) {
            LOG.debug("Current CERN HR db transaction is not active");
            return;
        }

        sf.getCurrentSession().getTransaction().commit();

    } catch (RollbackException e) {
        LOG.error("Error committing CERN HR db transaction: " + e.getMessage(), e);

        try {
            sf.getCurrentSession().getTransaction().rollback();
        } catch (PersistenceException pe) {
            LOG.error("Error rolling back CERN HR db transaction: " + pe.getMessage(), pe);
        }

    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);

    } finally {

        if (sf.getCurrentSession() != null) {
            try {
                sf.getCurrentSession().close();
            } catch (HibernateException e) {
                LOG.error("Error closing CERN HR db session: " + e.getMessage(), e);
            }
        }
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Sets the target object to read-write, allowing Hibernate to dirty check it and auto-flush changes.
 *
 * @see #setObjectToReadyOnly(Object, org.hibernate.SessionFactory)
 *
 * @param target The target object//w ww  .  j  a va2 s .  c om
 * @param sessionFactory The SessionFactory instance
 */
public static void setObjectToReadWrite(final Object target, SessionFactory sessionFactory) {
    Session session = sessionFactory.getCurrentSession();
    if (!canModifyReadWriteState(session, target)) {
        return;
    }

    SessionImplementor sessionImpl = (SessionImplementor) session;
    EntityEntry ee = sessionImpl.getPersistenceContext().getEntry(target);

    if (ee == null || ee.getStatus() != Status.READ_ONLY) {
        return;
    }

    Object actualTarget = target;
    if (target instanceof HibernateProxy) {
        actualTarget = ((HibernateProxy) target).getHibernateLazyInitializer().getImplementation();
    }

    session.setReadOnly(actualTarget, false);
    session.setFlushMode(FlushMode.AUTO);
    incrementVersion(target);
}

From source file:org.granite.tide.hibernate.HibernatePersistenceAdapter.java

License:Open Source License

public HibernatePersistenceAdapter(SessionFactory sessionFactory) {
    this.session = sessionFactory.getCurrentSession();
}

From source file:org.horizontaldb.shard.hibernate.AbstractDaoEnricher.java

License:Apache License

private ContextFrame getNewFrame(ShardContext shardContext) {
    SessionFactory sessionFactory = txManager.getSessionFactory();

    Session session = sessionFactory.getCurrentSession();

    return new ContextFrame(shardContext, session);
}

From source file:org.horizontaldb.shard.hibernate.AbstractDaoEnricherTest.java

License:Apache License

@Test
public void shouldSetAndUnsetSessionForDao() {
    AbstractDaoEnricher enricher = new AbstractDaoEnricher(txManager);

    ShardContext shardContext = new ShardContext("testClient");
    SessionFactory mockSessionFactory = EasyMock.createMock(SessionFactory.class);
    Session mockSession = EasyMock.createMock("mockSession", Session.class);
    AbstractDao mockDao = EasyMock.createMock("mockDao", AbstractDao.class);

    // called during statistics logging
    expect(mockSession.getSessionFactory()).andReturn(mockSessionFactory);
    expect(mockSessionFactory.getStatistics()).andReturn(null);
    // called during statistics logging

    expect(txManager.getSessionFactory()).andReturn(mockSessionFactory);
    expect(mockSessionFactory.getCurrentSession()).andReturn(mockSession);
    // setup//from   w w  w  .ja v  a2s .  co  m
    mockDao.setSession(mockSession);
    // tearDown
    mockDao.setSession(null);

    replay(txManager, mockSessionFactory, mockSession, mockDao);

    enricher.setup(mockDao, shardContext);

    enricher.tearDown(mockDao, shardContext);

    verify(txManager, mockSessionFactory, mockSession, mockDao);
}