Java 类org.hibernate.SessionFactory 实例源码

项目:lambda-rds-mysql    文件:HibernateUtil.java   
public static SessionFactory getSessionFactory() {
    if (null != sessionFactory)
        return sessionFactory;

    Configuration configuration = new Configuration();

    String jdbcUrl = "jdbc:mysql://"
            + System.getenv("RDS_HOSTNAME")
            + "/"
            + System.getenv("RDS_DB_NAME");

    configuration.setProperty("hibernate.connection.url", jdbcUrl);
    configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME"));
    configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD"));

    configuration.configure();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    try {
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        System.err.println("Initial SessionFactory creation failed." + e);
        throw new ExceptionInInitializerError(e);
    }
    return sessionFactory;
}
项目:java-p6spy    文件:HibernateTest.java   
@Test
public void withActiveSpanOnlyNoParent() throws InterruptedException {
  SessionFactory sessionFactory = createSessionFactory(";traceWithActiveSpanOnly=true");
  Session session = sessionFactory.openSession();

  Employee employee = new Employee();
  session.beginTransaction();
  session.save(employee);
  session.getTransaction().commit();
  session.close();
  sessionFactory.close();

  List<MockSpan> finishedSpans = mockTracer.finishedSpans();
  assertEquals(0, finishedSpans.size());

  assertNull(mockTracer.scopeManager().active());
}
项目:lams    文件:SpringSessionSynchronization.java   
public SpringSessionSynchronization(
        SessionHolder sessionHolder, SessionFactory sessionFactory,
        SQLExceptionTranslator jdbcExceptionTranslator, boolean newSession) {

    this.sessionHolder = sessionHolder;
    this.sessionFactory = sessionFactory;
    this.jdbcExceptionTranslator = jdbcExceptionTranslator;
    this.newSession = newSession;

    // Check whether the SessionFactory has a JTA TransactionManager.
    TransactionManager jtaTm =
            SessionFactoryUtils.getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
    if (jtaTm != null) {
        this.hibernateTransactionCompletion = true;
        // Fetch current JTA Transaction object
        // (just necessary for JTA transaction suspension, with an individual
        // Hibernate Session per currently active/suspended transaction).
        try {
            this.jtaTransaction = jtaTm.getTransaction();
        }
        catch (SystemException ex) {
            throw new DataAccessResourceFailureException("Could not access JTA transaction", ex);
        }
    }
}
项目:hibernate-ogm-redis    文件:RedisTestHelper.java   
@Override
public long getNumberOfEntities(SessionFactory sessionFactory) {
    RedisClusterCommands<String, String> connection = getConnection( sessionFactory );
    List<String> keys = connection.keys( "*" );

    long result = 0;
    for ( String key : keys ) {
        if ( key.startsWith( AbstractRedisDialect.ASSOCIATIONS ) || key.startsWith( AbstractRedisDialect.IDENTIFIERS ) ) {
            continue;
        }

        String type = connection.type( key );

        if ( type.equals( "hash" ) || type.equals( "string" ) ) {
            result++;
        }
    }

    return result;
}
项目:hibernate-ogm-ignite    文件:IgniteTestHelper.java   
@Override
public long getNumberOfAssociations(SessionFactory sessionFactory) {
    int associationCount = 0;
    IgniteDatastoreProvider datastoreProvider = getProvider( sessionFactory );
    for ( CollectionPersister collectionPersister : ( (SessionFactoryImplementor) sessionFactory ).getCollectionPersisters().values() ) {
        AssociationKeyMetadata associationKeyMetadata = ( (OgmCollectionPersister) collectionPersister ).getAssociationKeyMetadata();
        if ( associationKeyMetadata.getAssociationKind() == AssociationKind.ASSOCIATION ) {
            IgniteCache<Object, BinaryObject> associationCache = getAssociationCache( sessionFactory, associationKeyMetadata );
            StringBuilder query = new StringBuilder( "SELECT " )
                                        .append( StringHelper.realColumnName( associationKeyMetadata.getColumnNames()[0] ) )
                                        .append( " FROM " ).append( associationKeyMetadata.getTable() );
            SqlFieldsQuery sqlQuery = datastoreProvider.createSqlFieldsQueryWithLog( query.toString(), null );
            Iterable<List<?>> queryResult = associationCache.query( sqlQuery );
            Set<Object> uniqs = new HashSet<>();
            for ( List<?> row : queryResult ) {
                Object value = row.get( 0 );
                if ( value != null ) {
                    uniqs.add( value );
                }
            }
            associationCount += uniqs.size();
        }
    }
    return associationCount;
}
项目:bdf2    文件:HibernateDao.java   
private int queryForInt(String hql,Object[] parameters,Map<String,Object> parameterMap,String dataSourceName){
    SessionFactory factory=this.getSessionFactory(dataSourceName);
    Session session=factory.openSession();
    int count=0;
    try{
        Query countQuery=session.createQuery(hql);
        if(parameters!=null){
            setQueryParameters(countQuery,parameters);              
        }else if(parameterMap!=null){
            setQueryParameters(countQuery,parameterMap);                                
        }
        Object countObj=countQuery.uniqueResult();
        if(countObj instanceof Long){
            count=((Long)countObj).intValue();
        }else if(countObj instanceof Integer){
            count=((Integer)countObj).intValue();
        }
    }finally{
        session.close();
    }
    return count;
}
项目:lams    文件:SessionFactoryUtils.java   
/**
 * Process all Hibernate Sessions that have been registered for deferred close
 * for the given SessionFactory.
 * @param sessionFactory the Hibernate SessionFactory to process deferred close for
 * @see #initDeferredClose
 * @see #releaseSession
 */
public static void processDeferredClose(SessionFactory sessionFactory) {
    Assert.notNull(sessionFactory, "No SessionFactory specified");
    Map<SessionFactory, Set<Session>> holderMap = deferredCloseHolder.get();
    if (holderMap == null || !holderMap.containsKey(sessionFactory)) {
        throw new IllegalStateException("Deferred close not active for SessionFactory [" + sessionFactory + "]");
    }
    logger.debug("Processing deferred close of Hibernate Sessions");
    Set<Session> sessions = holderMap.remove(sessionFactory);
    for (Session session : sessions) {
        closeSession(session);
    }
    if (holderMap.isEmpty()) {
        deferredCloseHolder.remove();
    }
}
项目:LibrarySystem    文件:TestAdmin.java   
@Test
public void testGetAdmin(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Admin admin = (Admin) session.get(Admin.class, 1);
    System.out.println(admin);
    System.out.println(admin.getAuthorization().getSuperSet());
    session.close();

}
项目:Equella    文件:HibernateMigrationService.java   
synchronized SessionFactory getSessionFactory()
{
    if( sessionFactory == null )
    {
        sessionFactory = getHibernateFactory().getSessionFactory();
    }
    return sessionFactory;
}
项目:NewsSystem    文件:NewsInfoDAOImpl.java   
/**
 * 获得记录总数
 */
@Override
public Integer getCountOfAllNewsInfo() {
    Session session = SessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(NewsInfo.class);
    return criteria.list().size();
}
项目:lams    文件:HibernateSessionManager.java   
private static SessionFactory getSessionFactory() {
if (HibernateSessionManager.sessionFactory == null) {
    WebApplicationContext wac = WebApplicationContextUtils
        .getRequiredWebApplicationContext(SessionManager.getServletContext());
    HibernateSessionManager.sessionFactory = (SessionFactory) wac.getBean("coreSessionFactory");
}
return HibernateSessionManager.sessionFactory;
   }
项目:hibernate-ogm-ignite    文件:IgniteTestHelper.java   
@Override
public void dropSchemaAndDatabase(SessionFactory sessionFactory) {
    if ( Ignition.allGrids().size() > 1 ) { // some tests doesn't stop DatastareProvider
        String currentGridName = getProvider( sessionFactory ).getGridName();
        for ( Ignite grid : Ignition.allGrids() ) {
            if ( !Objects.equals( currentGridName, grid.name() ) ) {
                grid.close();
            }
        }
    }
}
项目:LibrarySystem    文件:TestAdmin.java   
@Test
public void testSaveAdmin(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    Admin admin = new Admin();
    admin.setName("cairou");
    admin.setUsername("admin");
    admin.setPwd(Md5Utils.md5("admin"));
    session.save(admin);
    transaction.commit();
    session.close();
}
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:AppConfig.java   
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(
            sessionFactory);
    return transactionManager;
}
项目:bdf2    文件:HibernateSessionFactoryRepository.java   
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    sessionFactoryBeanList = applicationContext.getBeansOfType(HibernateSessionFactory.class)
            .values();
    for (HibernateSessionFactory bean : sessionFactoryBeanList) {
        SessionFactory sessionFactory = bean.getObject();
        sessionFactoryMap.put(bean.getDataSourceName(), sessionFactory);
        if (bean.isAsDefault()) {
            defaultSessionFactory = sessionFactory;
            defaultSessionFactoryName = bean.getDataSourceName();
        }
    }
}
项目:stroom-stats    文件:StatisticConfigurationServiceImpl.java   
@Inject
public StatisticConfigurationServiceImpl(final CacheFactory cacheFactory,
                                         final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO,
                                         final StatisticConfigurationCacheByUuidLoaderWriter byUuidLoaderWriter,
                                         final SessionFactory sessionFactory) {

    this.stroomStatsStoreEntityDAO = stroomStatsStoreEntityDAO;
    this.sessionFactory = sessionFactory;

    this.keyByUuidCache = cacheFactory.getOrCreateCache(
            KEY_BY_UUID_CACHE_NAME,
            String.class,
            StatisticConfiguration.class,
            Optional.of(byUuidLoaderWriter));
}
项目:LibrarySystem    文件:TestBorrow.java   
@Test
public void testSaveBorrow(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();

    BorrowInfo borrowInfo = new BorrowInfo();
    Admin admin = new Admin();
    admin.setAid(2);
    borrowInfo.setAdmin(admin);
    session.save(borrowInfo);

    transaction.commit();
    session.close();
}
项目:LibrarySystem    文件:TestAdmin.java   
@Test
public void testGetAdmin3(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Authorization authorization = (Authorization) session.get(Authorization.class, 1);
    System.out.println(authorization.getAdmin().getName());
    session.close();
}
项目:jeesupport    文件:AbsSupportDao.java   
protected Session _open_session( String _db ) {
    if ( sessionFactoryMap.containsKey( _db ) ) {
        SessionFactory sessFactory = sessionFactoryMap.get( _db );
        return sessFactory.openSession();
    }

    throw new NullPointerException( "没有找到数据库[" + _db + "]的对应Session容器,请检查配置文件中的[ " + DEFAULT_SFMAP + " ]是否正确。" );
}
项目:lams    文件:SessionFactoryObserverChain.java   
@Override
public void sessionFactoryClosed(SessionFactory factory) {
    if ( observers == null ) {
        return;
    }

    //notify in reverse order of create notification
    int size = observers.size();
    for (int index = size - 1 ; index >= 0 ; index--) {
        observers.get( index ).sessionFactoryClosed( factory );
    }
}
项目:OSWf-OSWorkflow-fork    文件:StartupContextListener.java   
private SessionFactory createSessionFactory() {

    SessionFactory sessionFactory = null;

    try {

        String resource;

        Configuration configuration = new Configuration();

        resource = "oswf-store.cfg.xml";
        logger.info("Configuring Hibernate Mapping: " + resource);
        configuration.configure(resource);

        // Database configuration; H2 or MySQL
        resource = "hibernate.xml";
        logger.info("Configuring Hibernate Mapping: " + resource);
        configuration.configure(resource);

        // Attempt to create the SessionFactory; exceptions may be thrown                
        sessionFactory =  configuration.buildSessionFactory();

    } catch (Throwable e) {
        logger.error(fatal, "Failed to create Hibernate SessionFactory: " + e.toString());
        sessionFactory = null;
    }

    return sessionFactory;
}
项目:lams    文件:SessionFactoryUtils.java   
/**
 * Close the given Session, created via the given factory,
 * if it is not managed externally (i.e. not bound to the thread).
 * @param session the Hibernate Session to close (may be {@code null})
 * @param sessionFactory Hibernate SessionFactory that the Session was created with
 * (may be {@code null})
 */
public static void releaseSession(Session session, SessionFactory sessionFactory) {
    if (session == null) {
        return;
    }
    // Only close non-transactional Sessions.
    if (!isSessionTransactional(session, sessionFactory)) {
        closeSessionOrRegisterDeferredClose(session, sessionFactory);
    }
}
项目:lams    文件:OpenSessionInViewFilter.java   
/**
 * Look up the SessionFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the SessionFactory to use
 * @see #getSessionFactoryBeanName
 */
protected SessionFactory lookupSessionFactory() {
    if (logger.isDebugEnabled()) {
        logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
    }
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}
项目:OSWf-OSWorkflow-fork    文件:HibernateStore.java   
public HibernateStore(Map<String,String> config, Map<String,Object> parameters) throws WorkflowStoreException {
    super(config, parameters);

    sessionFactory = (SessionFactory)parameters.get("sessionFactory");

    if(sessionFactory == null)
        throw new WorkflowStoreException("Hibernate SessionFactory not configured in persistence store");
}
项目:lams    文件:SessionFactoryUtils.java   
/**
 * Get a new Hibernate Session from the given SessionFactory.
 * Will return a new Session even if there already is a pre-bound
 * Session for the given SessionFactory.
 * <p>Within a transaction, this method will create a new Session
 * that shares the transaction's JDBC Connection. More specifically,
 * it will use the same JDBC Connection as the pre-bound Hibernate Session.
 * @param sessionFactory Hibernate SessionFactory to create the session with
 * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none
 * @return the new Session
 */
@SuppressWarnings("deprecation")
public static Session getNewSession(SessionFactory sessionFactory, Interceptor entityInterceptor) {
    Assert.notNull(sessionFactory, "No SessionFactory specified");

    try {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
        if (sessionHolder != null && !sessionHolder.isEmpty()) {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection(), entityInterceptor);
            }
            else {
                return sessionFactory.openSession(sessionHolder.getAnySession().connection());
            }
        }
        else {
            if (entityInterceptor != null) {
                return sessionFactory.openSession(entityInterceptor);
            }
            else {
                return sessionFactory.openSession();
            }
        }
    }
    catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}
项目:LibrarySystem    文件:TestBook.java   
@Test
public void testFindBook(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    String hql= "from Book";
    List createQuery = session.createQuery(hql).list();
    Book book = (Book) createQuery.get(0);
    System.out.println(book);
    System.out.println(book.getBookType());
}
项目:bdf2    文件:CalendarMaintain.java   
@DataResolver
public void saveCalendars(Collection<JobCalendar> calendars){
    SessionFactory sessionFactory=this.getSessionFactory();
    Session session=sessionFactory.openSession();
    try{
        for(JobCalendar c:calendars){
            EntityState state=EntityUtils.getState(c);
            if(state.equals(EntityState.NEW)){
                c.setId(UUID.randomUUID().toString());
                c.setCompanyId(dataService.getCompanyId());
                session.save(c);
            }
            if(state.equals(EntityState.MODIFIED)){
                session.update(c);
            }
            if(state.equals(EntityState.DELETED)){
                String hql="select count(*) from "+JobCalendarRelation.class.getName()+" where calendarId=:calendarId";
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("calendarId", c.getId());
                int count=this.queryForInt(hql, map);
                if(count>0){
                    throw new RuntimeException("当前日期有Job正在使用,不能被删除");
                }
                hql="delete "+JobCalendarDate.class.getName()+" where calendarId=:calendarId";
                session.createQuery(hql).setString("calendarId", c.getId()).executeUpdate();
                session.delete(c);
            }
            if(c.getCalendarDates()!=null){
                this.saveCalendarDates(c.getCalendarDates(), session);
            }
        }
    }finally{
        session.flush();
        session.close();
    }
}
项目:LibrarySystem    文件:TestAdmin.java   
@Test
public void testSaveAdmin3(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    Authorization authorization = new Authorization();

    authorization.setAid(2);
    session.save(authorization);

    transaction.commit();
    session.close();
}
项目:sbc-qsystem    文件:Spring.java   
public SessionFactory getSessionFactory() {
    return getTxManager().getSessionFactory();
}
项目:uflo    文件:HeartJobDetail.java   
public SessionFactory getSessionFactory() {
    return sessionFactory;
}
项目:theLXGweb    文件:playerDaoImpl.java   
@Autowired
public playerDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
项目:sjk    文件:AbstractBaseDao.java   
public void setSessions(SessionFactory sessions) {
    this.sessions = sessions;
}
项目:theLXGweb    文件:votesDaoImpl.java   
@Autowired
public votesDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
项目:theLXGweb    文件:KnockoutScoreDaoImpl.java   
@Autowired
public KnockoutScoreDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
项目:bdf2    文件:HibernateSessionFactoryRepository.java   
public SessionFactory getDefaultSessionFactory() {
    return defaultSessionFactory;
}
项目:rjb-blog-multitenancy    文件:AbstractHibernateDao.java   
public AbstractHibernateDao(Class<T> entityClass, SessionFactory sessionFactory) {
    this.entityClass = entityClass;
    this.sessionFactory = sessionFactory;
}
项目:baseframe-partition    文件:BasePartitionService.java   
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
项目:cr-private-server    文件:PlayerService.java   
public PlayerService(SessionFactory sessionFactory) {
    super(sessionFactory);
}
项目:Restaurant    文件:ProductDaoImpl.java   
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
项目:baseframe-partition    文件:DaoMethodPreHandler.java   
public DaoMethodPreHandler(SessionFactory sessionFactory) {
    this.dao = new HibernatePartitionDaoImpl(sessionFactory);
}