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.apache.tapestry5.internal.hibernate.HibernateSessionSourceImplTest.java

License:Apache License

@Test
public void startup_without_packages() {
    Collection<String> packageNames = CollectionFactory.newList("org.example.myapp.entities",
            "org.example.app0.entities");
    HibernateEntityPackageManager packageManager = newMock(HibernateEntityPackageManager.class);
    TestBase.expect(packageManager.getPackageNames()).andReturn(packageNames);

    ClasspathScannerImpl scanner = new ClasspathScannerImpl(new ClasspathURLConverterImpl());
    ClassNameLocatorImpl classNameLocator = new ClassNameLocatorImpl(scanner);

    List<HibernateConfigurer> filters = Arrays.asList(new DefaultHibernateConfigurer(true),
            new PackageNameHibernateConfigurer(packageManager, classNameLocator));

    replay();//  ww  w.j a  v a2 s . c  o m

    HibernateSessionSource source = new HibernateSessionSourceImpl(log, filters);

    Session session = source.create();
    Assert.assertNotNull(session);

    // make sure it found the entity in the package
    ClassMetadata meta = session.getSessionFactory().getClassMetadata(User.class);
    Assert.assertEquals(meta.getEntityName(), "org.example.app0.entities.User");

    verify();
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

License:Apache License

@AggrEventsTransactional
@Override//  ww  w.  j a va 2s  .  c  om
public void evictAggregates(Map<Class<?>, Collection<Serializable>> entitiesToEvict) {
    int evictedEntities = 0;
    int evictedCollections = 0;

    final Session session = getEntityManager().unwrap(Session.class);
    final SessionFactory sessionFactory = session.getSessionFactory();
    final Cache cache = sessionFactory.getCache();

    for (final Entry<Class<?>, Collection<Serializable>> evictedEntityEntry : entitiesToEvict.entrySet()) {
        final Class<?> entityClass = evictedEntityEntry.getKey();
        final List<String> collectionRoles = getCollectionRoles(sessionFactory, entityClass);

        for (final Serializable id : evictedEntityEntry.getValue()) {
            cache.evictEntity(entityClass, id);
            evictedEntities++;

            for (final String collectionRole : collectionRoles) {
                cache.evictCollection(collectionRole, id);
                evictedCollections++;
            }
        }
    }

    logger.debug("Evicted {} entities and {} collections from hibernate caches", evictedEntities,
            evictedCollections);
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

License:Apache License

private EventProcessingResult doAggregateRawEventsInternal() {
    if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME
                + " must be owned by the current thread and server");
    }//from   w  w  w  .  ja va2 s  .  c  o m

    if (!this.portalEventDimensionPopulator.isCheckedDimensions()) {
        //First time aggregation has happened, run populateDimensions to ensure enough dimension data exists
        final boolean populatedDimensions = this.portalEventAggregationManager.populateDimensions();
        if (!populatedDimensions) {
            this.logger.warn(
                    "Aborting raw event aggregation, populateDimensions returned false so the state of date/time dimensions is unknown");
            return null;
        }
    }

    //Flush any dimension creation before aggregation
    final EntityManager entityManager = this.getEntityManager();
    entityManager.flush();
    entityManager.setFlushMode(FlushModeType.COMMIT);

    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.AGGREGATION, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    final String previousServerName = eventAggregatorStatus.getServerName();
    if (previousServerName != null && !serverName.equals(previousServerName)) {
        this.logger.debug("Last aggregation run on {} clearing all aggregation caches", previousServerName);
        final Session session = getEntityManager().unwrap(Session.class);
        final Cache cache = session.getSessionFactory().getCache();
        cache.evictEntityRegions();
    }

    eventAggregatorStatus.setServerName(serverName);

    //Calculate date range for aggregation
    DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    if (lastAggregated == null) {
        lastAggregated = portalEventDao.getOldestPortalEventTimestamp();

        //No portal events to aggregate, skip aggregation
        if (lastAggregated == null) {
            return new EventProcessingResult(0, null, null, true);
        }

        //First time aggregation has run, initialize the CLEAN_UNCLOSED status to save catch-up time
        final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao
                .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.CLEAN_UNCLOSED, true);
        AggregationIntervalInfo oldestMinuteInterval = this.intervalHelper
                .getIntervalInfo(AggregationInterval.MINUTE, lastAggregated);
        cleanUnclosedStatus.setLastEventDate(oldestMinuteInterval.getStart().minusMinutes(1));
        eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);
    }

    final DateTime newestEventTime = DateTime.now().minus(this.aggregationDelay).secondOfMinute()
            .roundFloorCopy();

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    final MutableInt events = new MutableInt();
    final MutableObject lastEventDate = new MutableObject(newestEventTime);

    boolean complete;
    try {
        currentThread.setName(currentName + "-" + lastAggregated + "_" + newestEventTime);

        logger.debug("Starting aggregation of events between {} (inc) and {} (exc)", lastAggregated,
                newestEventTime);

        //Do aggregation, capturing the start and end dates
        eventAggregatorStatus.setLastStart(DateTime.now());

        complete = portalEventDao.aggregatePortalEvents(lastAggregated, newestEventTime,
                this.eventAggregationBatchSize,
                new AggregateEventsHandler(events, lastEventDate, eventAggregatorStatus));

        eventAggregatorStatus.setLastEventDate((DateTime) lastEventDate.getValue());
        eventAggregatorStatus.setLastEnd(DateTime.now());
    } finally {
        currentThread.setName(currentName);
    }

    //Store the results of the aggregation
    eventAggregationManagementDao.updateEventAggregatorStatus(eventAggregatorStatus);

    complete = complete
            && (this.eventAggregationBatchSize <= 0 || events.intValue() < this.eventAggregationBatchSize);
    return new EventProcessingResult(events.intValue(), lastAggregated,
            eventAggregatorStatus.getLastEventDate(), complete);
}

From source file:org.azrul.langkuik.dao.HibernateGenericDAO.java

public <P> Collection<T> searchResultAlreadyInParent(Collection<T> searchResult, Class<T> daoClass,
        P parentObject, String parentToChildrenField) {
    try {//  www .j  a  v a2  s  .co m
        EntityManager em = emf.createEntityManager();

        Session session = (Session) em.getDelegate();
        String currentIdField = session.getSessionFactory().getClassMetadata(daoClass)
                .getIdentifierPropertyName();

        Collection searchResultIds = new ArrayList();
        for (T a : searchResult) {
            Field idField = a.getClass().getDeclaredField(currentIdField);
            idField.setAccessible(true);
            searchResultIds.add(idField.get(a));
        }

        CriteriaBuilder cb = em.getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery<T> criteria = cb.createQuery(daoClass);
        Root parent = criteria.from(parentObject.getClass());
        Join join = parent.join(parentToChildrenField);

        criteria.select(join)
                .where(cb.and(cb.equal(parent, parentObject), join.get(currentIdField).in(searchResultIds)));
        List<T> filteredSearchResult = em.createQuery(criteria).getResultList();
        session.close();

        return filteredSearchResult;
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(HibernateGenericDAO.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(HibernateGenericDAO.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(HibernateGenericDAO.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(HibernateGenericDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new ArrayList<T>();
}

From source file:org.beangle.commons.orm.hibernate.internal.SessionUtils.java

License:Open Source License

public static void closeSession(Session session) {
    try {/* w w w. j  av a  2 s.co m*/
        SessionHolder holder = (SessionHolder) TransactionSynchronizationManager
                .getResource(session.getSessionFactory());
        if (null != holder) {
            TransactionSynchronizationManager.unbindResource(session.getSessionFactory());
        }
        session.close();
    } catch (HibernateException ex) {
        logger.debug("Could not close Hibernate Session", ex);
    } catch (Throwable ex) {
        logger.debug("Unexpected exception on closing Hibernate Session", ex);
    }
}

From source file:org.beangle.orm.hibernate.internal.SessionUtils.java

License:Open Source License

public static void closeSession(Session session) {
    try {/* w  w w .j  a  v  a  2  s .c  o m*/
        SessionHolder holder = (SessionHolder) getResource(session.getSessionFactory());
        if (null != holder)
            unbindResource(session.getSessionFactory());
        session.close();
    } catch (HibernateException ex) {
        logger.debug("Could not close Hibernate Session", ex);
    } catch (Throwable ex) {
        logger.debug("Unexpected exception on closing Hibernate Session", ex);
    }
}

From source file:org.biomojo.util.DbUtil.java

License:Open Source License

/**
 * Log stats./*from w w  w .  ja v  a2s  . c om*/
 *
 * @param comment
 *            the comment
 */
public void logStats(final String comment) {
    if (entityManager instanceof HibernateEntityManager) {
        final Session session = ((HibernateEntityManager) entityManager).getSession();
        logger.info("STATS: " + comment);
        session.getSessionFactory().getStatistics().logSummary();
    } else {
        logger.warn("Entity Manager is not a hibernate entity manager");
    }
}

From source file:org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl.java

License:Apache License

@Override
public Field getIdField(Class<?> clazz, Session session) {
    clazz = getNonProxyImplementationClassIfNecessary(clazz);
    ClassMetadata metadata = session.getSessionFactory().getClassMetadata(clazz);
    Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName());
    idField.setAccessible(true);/*from   www  . j a  v a2  s.  c o m*/
    return idField;
}

From source file:org.candlepin.resteasy.filter.CandlepinQueryInterceptor.java

License:Open Source License

/**
 * Opens a new session from the current session's session factory.
 *
 * @return//www  .  j  a  v  a  2  s  . c o m
 *  a newly opened session
 */
protected Session openSession() {
    Session currentSession = (Session) this.emProvider.get().getDelegate();
    SessionFactory factory = currentSession.getSessionFactory();

    return factory.openSession();
}

From source file:org.candlepin.resteasy.filter.CandlepinQueryInterceptorTest.java

License:Open Source License

@Override
public void init() throws Exception {
    super.init();

    this.mockJsonProvider = mock(JsonProvider.class);
    this.mockJsonFactory = mock(JsonFactory.class);
    this.mockJsonGenerator = mock(JsonGenerator.class);
    this.mockObjectMapper = mock(ObjectMapper.class);
    this.mockOutputStream = mock(OutputStream.class);

    try {//ww  w . j  a va 2 s.co  m
        when(this.mockJsonProvider.locateMapper(any(Class.class), any(MediaType.class)))
                .thenReturn(this.mockObjectMapper);

        when(this.mockObjectMapper.getJsonFactory()).thenReturn(this.mockJsonFactory);

        when(this.mockJsonFactory.createGenerator(eq(this.mockOutputStream)))
                .thenReturn(this.mockJsonGenerator);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // This entire block of mock objects is present to workaround a deadlock issue that occurs
    // when attempting to execute two queries against the same table with cursors and lazy
    // properties via hsqldb.
    this.emProvider = mock(Provider.class);
    Session currentSession = (Session) this.getEntityManager().getDelegate();
    Session wrappedSession = spy(new SessionWrapper(currentSession));
    EntityManager mockEntityManager = mock(EntityManager.class);
    Session mockSession = mock(Session.class);
    SessionFactory mockSessionFactory = mock(SessionFactory.class);

    when(this.emProvider.get()).thenReturn(mockEntityManager);
    when(mockEntityManager.getDelegate()).thenReturn(mockSession);
    when(mockSession.getSessionFactory()).thenReturn(mockSessionFactory);
    when(mockSessionFactory.openSession()).thenReturn(wrappedSession);
    doNothing().when(wrappedSession).close();

    // Create some owners to play with
    for (int i = 0; i < 5; ++i) {
        this.createOwner("test-owner-" + (i + 1), "Test Owner " + (i + 1));
    }

    // Make sure we don't leave any page request on the context to muck with other tests
    ResteasyProviderFactory.popContextData(PageRequest.class);
}