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.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

License:Apache License

/**
 * Execute schema creation script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaValidator class, to be invoked after application startup.
 * <p>Fetch the FactoryBean itself by rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * <pre class="code">/*w  ww .  j  av  a 2  s.c o  m*/
 * LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 * </pre>
 * or in the case of {@code @Configuration} class usage, register the
 * SessionFactoryBuilder as a {@code @Bean} and fetch it by type:
 * <pre class="code">
 * SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 * </pre>
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see org.hibernate.cfg.Configuration#validateSchema
 * @see org.hibernate.tool.hbm2ddl.SchemaValidator
 */
public void validateDatabaseSchema() throws DataAccessException {
    logger.info("Validating database schema for Hibernate SessionFactory");
    DataSource dataSource = getDataSource();
    if (dataSource != null) {
        // Make given DataSource available for the schema update.
        SessionFactoryBuilderSupport.configTimeDataSourceHolder.set(dataSource);
    }
    try {
        HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory());
        hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @SuppressWarnings("deprecation")
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect();
                DatabaseMetadata metadata = new DatabaseMetadata(session.connection(), dialect);
                configuration.validateSchema(dialect, metadata);
                return null;
            }
        });
    } finally {
        if (dataSource != null) {
            SessionFactoryBuilderSupport.configTimeDataSourceHolder.remove();
        }
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

License:Apache License

/**
 * Execute schema drop script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaExport class, to be invoked on application setup.
 * <p>Fetch the FactoryBean itself by rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * <pre class="code">/*from  w ww.j a va  2  s . c  om*/
 * LocalSessionFactoryBean sfb = ctx.getBean("&mySessionFactory", LocalSessionFactoryBean.class);
 * </pre>
 * or in the case of {@code @Configuration} class usage, register the
 * SessionFactoryBuilder as a {@code @Bean} and fetch it by type:
 * <pre class="code">
 * SessionFactoryBuilder sfb = ctx.getBean(SessionFactoryBuilder.class);
 * </pre>
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws org.springframework.dao.DataAccessException in case of script execution errors
 * @see org.hibernate.cfg.Configuration#generateDropSchemaScript
 * @see org.hibernate.tool.hbm2ddl.SchemaExport#drop
 */
public void dropDatabaseSchema() throws DataAccessException {
    logger.info("Dropping database schema for Hibernate SessionFactory");
    HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory());
    hibernateTemplate.execute(new HibernateCallback<Object>() {
        @SuppressWarnings("deprecation")
        public Void doInHibernate(Session session) throws HibernateException, SQLException {
            Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect();
            String[] sql = configuration.generateDropSchemaScript(dialect);
            executeSchemaScript(session.connection(), sql);
            return null;
        }
    });
}

From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java

License:Apache License

/**
 * Try to retrieve the JTA TransactionManager from the given SessionFactory
 * and/or Session. Check the passed-in SessionFactory for implementing
 * SessionFactoryImplementor (the usual case), falling back to the
 * SessionFactory reference that the Session itself carries.
 * @param sessionFactory Hibernate SessionFactory
 * @param session Hibernate Session (can also be {@code null})
 * @return the JTA TransactionManager, if any
 * @see javax.transaction.TransactionManager
 * @see SessionFactoryImplementor#getTransactionManager
 * @see Session#getSessionFactory/*from   w  ww  . j  a v a2  s .  c o  m*/
 * @see org.hibernate.impl.SessionFactoryImpl
 */
public static TransactionManager getJtaTransactionManager(SessionFactory sessionFactory, Session session) {
    SessionFactoryImplementor sessionFactoryImpl = null;
    if (sessionFactory instanceof SessionFactoryImplementor) {
        sessionFactoryImpl = ((SessionFactoryImplementor) sessionFactory);
    } else if (session != null) {
        SessionFactory internalFactory = session.getSessionFactory();
        if (internalFactory instanceof SessionFactoryImplementor) {
            sessionFactoryImpl = (SessionFactoryImplementor) internalFactory;
        }
    }
    return (sessionFactoryImpl != null ? sessionFactoryImpl.getTransactionManager() : null);
}

From source file:org.springframework.orm.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionWithPropagationSupports() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);

    given(sf.openSession()).willReturn(session);
    given(session.getSessionFactory()).willReturn(sf);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override//from   ww w.  j ava 2s. com
        protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
            assertTrue("Is not new transaction", !status.isNewTransaction());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            Session session = sf.openSession();
            session.flush();
            session.close();
            return null;
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    InOrder ordered = inOrder(session);
    ordered.verify(session).flush();
    ordered.verify(session).close();
}

From source file:org.springframework.orm.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionWithPropagationSupportsAndCurrentSession() throws Exception {
    final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
    final Session session = mock(Session.class);

    given(sf.openSession()).willReturn(session);
    given(session.getSessionFactory()).willReturn(sf);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() {
        @Override/*from www . j av  a  2 s. co  m*/
        protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
            return sf;
        }
    };
    lsfb.afterPropertiesSet();
    final SessionFactory sfProxy = lsfb.getObject();

    PlatformTransactionManager tm = new HibernateTransactionManager(sfProxy);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
            assertTrue("Is not new transaction", !status.isNewTransaction());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            Session session = new SpringSessionContext(sf).currentSession();
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sfProxy));
            session.flush();
            return null;
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy));
    InOrder ordered = inOrder(session);
    ordered.verify(session).flush();
    ordered.verify(session).close();
}

From source file:org.squashtest.it.infrastructure.DeleteDataSetLoadStrategy.java

License:Open Source License

public Connection getConnection(Session session) {
    try {/*from   ww w  .ja  v  a  2 s .c o  m*/
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider cp = sfi.getConnectionProvider();
        return cp.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

License:Open Source License

public static void clearCache(Class persistentClass, boolean evictQueries) {
    _RootDAO dao = new _RootDAO();
    org.hibernate.Session hibSession = dao.getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    if (persistentClass == null) {
        for (Iterator i = hibSessionFactory.getAllClassMetadata().entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            String className = (String) entry.getKey();
            ClassMetadata classMetadata = (ClassMetadata) entry.getValue();
            try {
                hibSessionFactory.getCache().evictEntityRegion(Class.forName(className));
                for (int j = 0; j < classMetadata.getPropertyNames().length; j++) {
                    if (classMetadata.getPropertyTypes()[j].isCollectionType()) {
                        try {
                            hibSessionFactory.getCache().evictCollectionRegion(
                                    className + "." + classMetadata.getPropertyNames()[j]);
                        } catch (MappingException e) {
                        }/*from   w ww.jav a2 s .c o m*/
                    }
                }
            } catch (ClassNotFoundException e) {
            }
        }
        hibSessionFactory.getCache().evictEntityRegions();
        hibSessionFactory.getCache().evictCollectionRegions();
    } else {
        ClassMetadata classMetadata = hibSessionFactory.getClassMetadata(persistentClass);
        hibSessionFactory.getCache().evictEntityRegion(persistentClass);
        if (classMetadata != null) {
            for (int j = 0; j < classMetadata.getPropertyNames().length; j++) {
                if (classMetadata.getPropertyTypes()[j].isCollectionType()) {
                    try {
                        hibSessionFactory.getCache().evictCollectionRegion(persistentClass.getClass().getName()
                                + "." + classMetadata.getPropertyNames()[j]);
                    } catch (MappingException e) {
                    }
                }
            }
        }
    }
    if (evictQueries) {
        hibSessionFactory.getCache().evictQueryRegions();
        hibSessionFactory.getCache().evictDefaultQueryRegion();
    }
}

From source file:org.unitime.timetable.model.ExamType.java

License:Open Source License

public static void refreshSolution(Long sessionId, Long examTypeId) {
    org.hibernate.Session hibSession = ExamTypeDAO.getInstance().getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    for (Long examId : (List<Long>) hibSession.createQuery(
            "select x.uniqueId from Exam x where x.session.uniqueId = :sessionId and x.examType.uniqueId = :examTypeId")
            .setLong("sessionId", sessionId).setLong("examTypeId", examTypeId).setCacheable(true).list()) {
        hibSessionFactory.getCache().evictEntity(Exam.class, examId);
        hibSessionFactory.getCache().evictCollection(Exam.class.getName() + ".assignedRooms", examId);
        hibSessionFactory.getCache().evictCollection(Exam.class.getName() + ".conflicts", examId);
    }//www . j av a2 s  .  c  om
    for (Long eventId : (List<Long>) hibSession.createQuery(
            "select e.uniqueId from ExamEvent e inner join e.exam x where x.session.uniqueId = :sessionId and x.examType.uniqueId = :examTypeId")
            .setLong("sessionId", sessionId).setLong("examTypeId", examTypeId).setCacheable(true).list()) {
        hibSessionFactory.getCache().evictEntity(Event.class, eventId);
        hibSessionFactory.getCache().evictCollection(Event.class.getName() + ".meetings", eventId);
    }
    hibSessionFactory.getCache().evictDefaultQueryRegion();
}

From source file:org.unitime.timetable.model.Solution.java

License:Open Source License

public static void refreshSolution(Long solutionId) {
    SolutionDAO dao = new SolutionDAO();
    org.hibernate.Session hibSession = dao.getSession();
    SessionFactory hibSessionFactory = hibSession.getSessionFactory();
    hibSessionFactory.getCache().evictEntity(Solution.class, solutionId);
    hibSessionFactory.getCache().evictCollection(Solution.class.getName() + ".parameters", solutionId);
    hibSessionFactory.getCache().evictCollection(Solution.class.getName() + ".assignments", solutionId);
    for (Iterator i = hibSession
            .createQuery("select c.uniqueId from " + "Class_ c, Solution s where s.uniqueId=:solutionId and "
                    + "c.managingDept.uniqueId in elements (s.owner.departments)")
            .setLong("solutionId", solutionId.longValue()).iterate(); i.hasNext();) {
        Number classId = (Number) i.next();
        hibSessionFactory.getCache().evictEntity(Class_.class, classId);
        hibSessionFactory.getCache().evictCollection(Class_.class.getName() + ".assignments", classId);
    }/*from w  w w .j av  a  2 s.c  o  m*/
    hibSessionFactory.getCache().evictCollection(SolverGroup.class.getName() + ".solutions",
            (Long) hibSession.createQuery("select owner.uniqueId from Solution s where s.uniqueId=:solutionId")
                    .setLong("solutionId", solutionId).uniqueResult());
}

From source file:org.unitime.timetable.model.StudentSectioningPref.java

License:Apache License

public static void updateStudentSectioningPreferences() {
    org.hibernate.Session hibSession = new _RootDAO().createNewSession();
    Transaction tx = hibSession.beginTransaction();
    try {//from w  w w .j  a  v  a  2  s  .  c o m
        boolean first = true;
        for (CourseRequestOption option : (List<CourseRequestOption>) hibSession
                .createQuery("from CourseRequestOption where optionType = :type")
                .setInteger("type",
                        OnlineSectioningLog.CourseRequestOption.OptionType.REQUEST_PREFERENCE.getNumber())
                .list()) {
            if (first) {
                Debug.info(" - Updating student scheduling preferences ...");
                first = false;
            }
            CourseRequest cr = option.getCourseRequest();
            hibSession.delete(option);
            cr.getCourseRequestOptions().remove(option);
            if (cr.getPreferences() == null)
                cr.setPreferences(new HashSet<StudentSectioningPref>());
            try {
                OnlineSectioningLog.CourseRequestOption pref = option.getOption();
                if (pref != null) {
                    if (pref.getInstructionalMethodCount() > 0) {
                        for (OnlineSectioningLog.Entity e : pref.getInstructionalMethodList()) {
                            boolean required = false;
                            if (e.getParameterCount() > 0)
                                for (OnlineSectioningLog.Property p : e.getParameterList())
                                    if ("required".equals(p.getKey()))
                                        required = "true".equals(p.getValue());
                            InstructionalMethod im = InstructionalMethodDAO.getInstance().get(e.getUniqueId());
                            if (im == null)
                                im = InstructionalMethod.findByReference(e.getName(), hibSession);
                            if (im != null) {
                                StudentInstrMthPref imp = new StudentInstrMthPref();
                                imp.setCourseRequest(cr);
                                imp.setRequired(required);
                                imp.setInstructionalMethod(im);
                                imp.setLabel(im.getReference());
                                cr.getPreferences().add(imp);
                            }
                        }
                    }
                    if (pref.getSectionCount() > 0) {
                        for (OnlineSectioningLog.Section x : pref.getSectionList()) {
                            boolean required = (x.hasPreference()
                                    && x.getPreference() == OnlineSectioningLog.Section.Preference.REQUIRED);
                            Class_ clazz = Class_DAO.getInstance().get(x.getClazz().getUniqueId(), hibSession);
                            if (clazz != null) {
                                StudentClassPref scp = new StudentClassPref();
                                scp.setCourseRequest(cr);
                                scp.setRequired(required);
                                scp.setClazz(clazz);
                                scp.setLabel(clazz.getClassPrefLabel(cr.getCourseOffering()));
                                cr.getPreferences().add(scp);
                            }
                        }
                    }
                }
            } catch (Exception e) {
            }
            hibSession.update(cr);
        }
        for (StudentInstrMthPref p : (List<StudentInstrMthPref>) hibSession.createQuery(
                "from StudentInstrMthPref where label is null and instructionalMethod.label is not null")
                .list()) {
            p.setLabel(p.getInstructionalMethod().getLabel());
            hibSession.update(p);
        }
        for (StudentClassPref p : (List<StudentClassPref>) hibSession
                .createQuery("from StudentClassPref where label is null").list()) {
            p.setLabel(p.getClazz().getClassPrefLabel(p.getCourseRequest().getCourseOffering()));
            hibSession.update(p);
        }
        tx.commit();
    } catch (Exception e) {
        Debug.error("Failed to update student sectioning preferences: " + e.getMessage(), e);
        tx.rollback();
    } finally {
        hibSession.getSessionFactory().getCache()
                .evictCollectionRegion(CourseRequest.class.getName() + ".courseRequestOptions");
        hibSession.close();
    }
}