Java 类org.hibernate.internal.SessionFactoryImpl 实例源码

项目:lams    文件:Configuration.java   
/**
 * Create a {@link SessionFactory} using the properties and mappings in this configuration. The
 * {@link SessionFactory} will be immutable, so changes made to {@code this} {@link Configuration} after
 * building the {@link SessionFactory} will not affect it.
 *
 * @param serviceRegistry The registry of services to be used in creating this session factory.
 *
 * @return The built {@link SessionFactory}
 *
 * @throws HibernateException usually indicates an invalid configuration or invalid mapping information
 */
public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException {
    LOG.debugf( "Preparing to build session factory with filters : %s", filterDefinitions );

    buildTypeRegistrations( serviceRegistry );
    secondPassCompile();
    if ( !metadataSourceQueue.isEmpty() ) {
        LOG.incompleteMappingMetadataCacheProcessing();
    }

    validate();

    Environment.verifyProperties( properties );
    Properties copy = new Properties();
    copy.putAll( properties );
    ConfigurationHelper.resolvePlaceHolders( copy );
    Settings settings = buildSettings( copy, serviceRegistry );

    return new SessionFactoryImpl(
            this,
            mapping,
            serviceRegistry,
            settings,
            sessionFactoryObserver
        );
}
项目:unitimes    文件:HibernateUtil.java   
public static void closeHibernate() {
    if (sSessionFactory!=null) {
        if (sSessionFactory instanceof SessionFactoryImpl) {
            ConnectionProvider cp = ((SessionFactoryImpl)sSessionFactory).getConnectionProvider();
            if (cp instanceof DisposableConnectionProvider) {
                try {
                    ((DisposableConnectionProvider)cp).destroy();
                } catch (Exception e) {
                    sLog.error("Failed to destroy connection provider: " + e.getMessage());
                }
            }
        }
        sSessionFactory.close();
        sSessionFactory=null;
    }
}
项目:mycore    文件:MCRHibernateConfigHelper.java   
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
    ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class);
    AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
    String qualifiedTableName = aep.getTableName();
    try (Session session = sessionFactoryImpl.openSession()) {
        session.doWork(connection -> {
            String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique")
                .flatMap(idx -> Stream.of("drop constraint if exists " + idx,
                    MessageFormat.format(
                        "add constraint {0} unique ({1}) deferrable initially deferred",
                        idx, getUniqueColumns(MCRCategoryImpl.class, idx))))
                .collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
            try (Statement stmt = connection.createStatement()) {
                LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
                stmt.execute(updateStmt);
            }
        });
    }
}
项目:hazelcast-hibernate5    文件:RegionFactoryDefaultSlowTest.java   
@Test
public void testQueryCacheCleanup() {

    MapConfig mapConfig = getHazelcastInstance(sf).getConfig().getMapConfig("org.hibernate.cache.*");
    final float baseEvictionRate = 0.2f;
    final int numberOfEntities = 100;
    final int defaultCleanupPeriod = 60;
    final int maxSize = mapConfig.getMaxSizeConfig().getSize();
    final int evictedItemCount = numberOfEntities - maxSize + (int) (maxSize * baseEvictionRate);
    insertDummyEntities(numberOfEntities);
    for (int i = 0; i < numberOfEntities; i++) {
        executeQuery(sf, i);
    }

    HazelcastQueryResultsRegion queryRegion = ((HazelcastQueryResultsRegion) (((SessionFactoryImpl) sf).getQueryCache()).getRegion());
    assertEquals(numberOfEntities, queryRegion.getCache().size());
    sleep(defaultCleanupPeriod);

    assertEquals(numberOfEntities - evictedItemCount, queryRegion.getCache().size());
}
项目:hazelcast-hibernate    文件:RegionFactoryDefaultSlowTest.java   
@Test
public void testQueryCacheCleanup() {

    MapConfig mapConfig = getHazelcastInstance(sf).getConfig().getMapConfig("org.hibernate.cache.*");
    final float baseEvictionRate = 0.2f;
    final int numberOfEntities = 100;
    final int defaultCleanupPeriod = 60;
    final int maxSize = mapConfig.getMaxSizeConfig().getSize();
    final int evictedItemCount = numberOfEntities - maxSize + (int) (maxSize * baseEvictionRate);
    insertDummyEntities(numberOfEntities);
    for (int i = 0; i < numberOfEntities; i++) {
        executeQuery(sf, i);
    }

    HazelcastQueryResultsRegion queryRegion = ((HazelcastQueryResultsRegion) (((SessionFactoryImpl) sf).getQueryCache()).getRegion());
    assertEquals(numberOfEntities, queryRegion.getCache().size());
    sleep(defaultCleanupPeriod);

    assertEquals(numberOfEntities - evictedItemCount, queryRegion.getCache().size());
}
项目:metaworks_framework    文件:FieldPathBuilder.java   
/**
 * This is a workaround for HHH-6562 (https://hibernate.atlassian.net/browse/HHH-6562)
 */
@SuppressWarnings("unchecked")
private void copyCollectionPersister(String originalKey, String copyKey,
        SessionFactoryImpl sessionFactory) {
    try {
        Field collectionPersistersField = SessionFactoryImpl.class
                .getDeclaredField("collectionPersisters");
        collectionPersistersField.setAccessible(true);
        Map collectionPersisters = (Map) collectionPersistersField.get(sessionFactory);
        if (collectionPersisters.containsKey(originalKey)) {
            Object collectionPersister = collectionPersisters.get(originalKey);
            collectionPersisters.put(copyKey, collectionPersister);
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:SparkCommerce    文件:FieldPathBuilder.java   
/**
 * This is a workaround for HHH-6562 (https://hibernate.atlassian.net/browse/HHH-6562)
 */
@SuppressWarnings("unchecked")
private void copyCollectionPersister(String originalKey, String copyKey,
        SessionFactoryImpl sessionFactory) {
    try {
        Field collectionPersistersField = SessionFactoryImpl.class
                .getDeclaredField("collectionPersisters");
        collectionPersistersField.setAccessible(true);
        Map collectionPersisters = (Map) collectionPersistersField.get(sessionFactory);
        if (collectionPersisters.containsKey(originalKey)) {
            Object collectionPersister = collectionPersisters.get(originalKey);
            collectionPersisters.put(copyKey, collectionPersister);
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:sdcct    文件:SdcctEntityManagerFactoryFactoryBean.java   
@Override
public EntityManagerFactoryImpl build() {
    SessionFactoryImpl sessionFactory =
        ((SessionFactoryImpl) (SdcctEntityManagerFactoryFactoryBean.this.entityManagerFactory = ((EntityManagerFactoryImpl) super.build()))
            .getSessionFactory());
    StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();

    serviceRegistry.getService(EntityManagerFactoryRef.class).setEntityManagerFactory(SdcctEntityManagerFactoryFactoryBean.this.entityManagerFactory);

    ContextHelper.getSearchintegratorBySFI(sessionFactory).getIndexBindings().replaceAll((entityClass, entityIndexBinding) -> {
        MutableEntityIndexBinding newEntityIndexBinding =
            new DefaultMutableEntityIndexBinding(entityIndexBinding.getSelectionStrategy(), entityIndexBinding.getSimilarity(),
                entityIndexBinding.getIndexManagers(), SdcctEntityManagerFactoryFactoryBean.this.entityIndexingInterceptor);
        newEntityIndexBinding.setDocumentBuilderIndexedEntity(entityIndexBinding.getDocumentBuilder());

        return newEntityIndexBinding;
    });

    serviceRegistry.getService(DbMetadataService.class);

    return SdcctEntityManagerFactoryFactoryBean.this.entityManagerFactory;
}
项目:blcdemo    文件:FieldPathBuilder.java   
/**
 * This is a workaround for HHH-6562 (https://hibernate.atlassian.net/browse/HHH-6562)
 */
@SuppressWarnings("unchecked")
private void copyCollectionPersister(String originalKey, String copyKey,
        SessionFactoryImpl sessionFactory) {
    try {
        Field collectionPersistersField = SessionFactoryImpl.class
                .getDeclaredField("collectionPersisters");
        collectionPersistersField.setAccessible(true);
        Map collectionPersisters = (Map) collectionPersistersField.get(sessionFactory);
        if (collectionPersisters.containsKey(originalKey)) {
            Object collectionPersister = collectionPersisters.get(originalKey);
            collectionPersisters.put(copyKey, collectionPersister);
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:unitime    文件:HibernateUtil.java   
public static void closeHibernate() {
    if (sSessionFactory!=null) {
        if (sSessionFactory instanceof SessionFactoryImpl) {
            ConnectionProvider cp = ((SessionFactoryImpl)sSessionFactory).getConnectionProvider();
            if (cp instanceof DisposableConnectionProvider) {
                try {
                    ((DisposableConnectionProvider)cp).destroy();
                } catch (Exception e) {
                    sLog.error("Failed to destroy connection provider: " + e.getMessage());
                }
            }
        }
        sSessionFactory.close();
        sSessionFactory=null;
    }
}
项目:jersey2-toolkit    文件:HibernateSessionFactoryFactory.java   
/**
 * Provide a singleton instance of the hibernate session factory.
 *
 * @return A session factory.
 */
@Override
public SessionFactory provide() {
    logger.trace("Creating hibernate session factory.");

    // Build the service registry.
    SessionFactory factory = new MetadataSources(serviceRegistry)
            .buildMetadata()
            .buildSessionFactory();

    // Register our event listeners.
    injectEventListeners(((SessionFactoryImpl) factory)
            .getServiceRegistry());

    return factory;
}
项目:flexy-pool    文件:ResourceLocalFlexyPoolHibernateConnectionProviderIntegrationTest.java   
@Test
public void testOverrideProperties() {
    getTransactionTemplate().execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus status) {
            Session session = getEntityManager().unwrap( Session.class );
            SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory();
            FlexyPoolHibernateConnectionProvider flexyPoolHibernateConnectionProvider =
                    (FlexyPoolHibernateConnectionProvider) sessionFactory.getConnectionProvider();
            FlexyPoolDataSource flexyPoolDataSource = ReflectionUtils.getFieldValue(
                    flexyPoolHibernateConnectionProvider,
                    "flexyPoolDataSource"
            );
            assertEquals( "abcd1234", ReflectionUtils.getFieldValue( flexyPoolDataSource, "uniqueName" ));

            return null;
        }
    });

}
项目:base-framework    文件:BasicHibernateDao.java   
/**
 * 根据hql创建Hibernate Query对象
 * 
 * @param queryOrNamedQuery hql 或者Hibernate的NamedQuery
 * @param values
 *            数量可变的参数,按顺序绑定.
 *            
 * @return {@link Query}
 */
protected Query createQuery(String queryOrNamedQuery, Object... values) {
    Assert.hasText(queryOrNamedQuery, "queryOrNamedQuery不能为空");

    SessionFactoryImpl factory = (SessionFactoryImpl) sessionFactory;
    NamedQueryDefinition nqd = factory.getNamedQuery( queryOrNamedQuery );
    Query query = null;

    if (nqd != null) {
        query = getSession().getNamedQuery(queryOrNamedQuery);
    } else {
        query = getSession().createQuery(queryOrNamedQuery);
    }

    setQueryValues(query, values);
    return query;
}
项目:base-framework    文件:BasicHibernateDao.java   
/**
 * 根据查询SQL与参数列表创建SQLQuery对象
 * 
 * @param queryOrNamedSQLQuery query 或者 NamedSQLQuery
 * @param values 数量可变的参数,按顺序绑定.
 *            
 * @return {@link SQLQuery}
 */
protected SQLQuery createSQLQuery( String queryOrNamedSQLQuery,  Object... values) {
    Assert.hasText(queryOrNamedSQLQuery, "queryOrNamedSQLQuery不能为空");
    SessionFactoryImpl factory = (SessionFactoryImpl) sessionFactory;
    NamedSQLQueryDefinition nsqlqd = factory.getNamedSQLQuery( queryOrNamedSQLQuery );
    Query query = null;

    if (nsqlqd != null) {
        query = getSession().getNamedQuery(queryOrNamedSQLQuery);
    } else {
        query = getSession().createSQLQuery(queryOrNamedSQLQuery);
    }

    setQueryValues(query, values);
    SQLQuery sqlQuery = (SQLQuery)query;

    return sqlQuery.addEntity(entityClass);
}
项目:debop4j    文件:HibernateTool.java   
/**
 * Register event listener.
 *
 * @param sessionFactory the session factory
 * @param listener       the listener
 * @param eventTypes     the event types
 */
@SuppressWarnings("unchecked")
public static void registerEventListener(SessionFactory sessionFactory, Object listener, EventType... eventTypes) {
    shouldNotBeNull(sessionFactory, "sessionFactory");
    shouldNotBeNull(listener, "listener");


        log.trace("sessionFactory에 event listener를 등록합니다... listener=[{}], eventTypes=[{}]",
                  listener, StringTool.listToString(eventTypes));

    EventListenerRegistry registry =
            ((SessionFactoryImpl) sessionFactory)
                    .getServiceRegistry()
                    .getService(EventListenerRegistry.class);

    for (EventType eventType : eventTypes) {
        try {
            registry.getEventListenerGroup(eventType).appendListener(listener);
        } catch (Exception ignored) {}
    }

}
项目:lams    文件:NamedProcedureCallDefinition.java   
public List<ParameterMemento> toMementos(SessionFactoryImpl sessionFactory) {
    final List<ParameterMemento> mementos = new ArrayList<ParameterMemento>();
    for ( ParameterDefinition definition : parameterDefinitions ) {
        mementos.add(definition.toMemento( sessionFactory ));
    }
    return mementos;
}
项目:lams    文件:NamedProcedureCallDefinition.java   
public ParameterMemento toMemento(SessionFactoryImpl sessionFactory) {
    return new ParameterMemento(
            position,
            name,
            parameterMode,
            type,
            sessionFactory.getTypeResolver().heuristicType( type.getName() )
    );
}
项目:Layer-Query    文件:CustomCriteriaQueryTranslator.java   
/**
 * REVISAR NIKOLAS
 */
@Override
public Type getType(Criteria subcriteria, String propertyName)
        throws HibernateException {
    System.out.println("Prperty name ==> "+propertyName);

    BasicType _type = ((SessionFactoryImpl) sessionFactory).getTypeResolver()
            .basic(rootCriteria.getMapColumns().get(propertyName).getType().getName());

    /*return getPropertyMapping( getEntityName( subcriteria, propertyName ) )
            .toType( getPropertyName( propertyName ) );*/
    return _type;
}
项目:mycore    文件:MCRHibernateConfigHelper.java   
public static void checkEntityManagerFactoryConfiguration(EntityManagerFactory entityManagerFactory) {
    try {
        SessionFactoryImpl sessionFactoryImpl = entityManagerFactory.unwrap(SessionFactoryImpl.class);
        if (PostgreSQL9Dialect.class
            .isInstance(sessionFactoryImpl.getServiceRegistry().getService(JdbcServices.class).getDialect())) {
            //fix ClassLeftUnique and ClassRightUnique, as PostgreSQL cannot evaluate them on statement level
            modifyConstraints(sessionFactoryImpl);
        }
    } catch (PersistenceException e) {
        LogManager.getLogger()
            .warn("Unsupported EntityManagerFactory found: {}", entityManagerFactory.getClass().getName());
    }
}
项目:devwars.tv    文件:DatabaseManager.java   
@Override
public void init() {
    boolean testing = Boolean.parseBoolean(System.getProperty("testing"));

    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    configuration.setInterceptor(new HibernateInterceptor());

    if (!testing) {
        configuration.setProperty("hibernate.connection.username", Reference.getEnvironmentProperty("db.username"));
        configuration.setProperty("hibernate.connection.password", Reference.getEnvironmentProperty("db.password"));
        String url = "jdbc:mysql://" + Reference.getEnvironmentProperty("db.host") + ":" + Reference.getEnvironmentProperty("db.port") + "/devwars";
        configuration.setProperty("hibernate.connection.url", url);
    } else {
        configuration.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
        configuration.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:testdb");
        configuration.setProperty("hibernate.connection.username", "sa");
        configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    }

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    EventListenerRegistry registry = ((SessionFactoryImpl) DatabaseManager.sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);

    registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(postLoadEvent ->
    {
        HibernateInterceptor.postLoadAny(postLoadEvent.getEntity());
        HibernateInterceptor.invokeMethodWithAnnotation(postLoadEvent.getEntity(), PostLoad.class);
    });
}
项目:mojito    文件:HibernateEventListenerConfig.java   
@PostConstruct
public void registerListeners() {
    EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
    SessionFactoryImpl sf = emf.getSessionFactory();
    EventListenerRegistry registry = (EventListenerRegistry)sf.getServiceRegistry().getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(entityCrudEventListener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(entityCrudEventListener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(entityCrudEventListener);
}
项目:mojito    文件:DDLGenerator.java   
@Test
public void generateCreateAnUpdateDDL() throws IOException {
    logger.debug("Generate create and update DDL");

    EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
    SessionFactoryImpl sf = emf.getSessionFactory();
    SessionFactoryServiceRegistryImpl serviceRegistry = (SessionFactoryServiceRegistryImpl) sf.getServiceRegistry();
    Configuration cfg = null;

    try {
        Field field = SessionFactoryServiceRegistryImpl.class.getDeclaredField("configuration");
        field.setAccessible(true);
        cfg = (Configuration) field.get(serviceRegistry);
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    Files.createDirectories(Paths.get("target/db/migration/"));

    SchemaUpdate update = new SchemaUpdate(serviceRegistry, cfg);
    update.setDelimiter(";");
    update.setOutputFile("target/db/migration/Vx__yy_zz.sql");
    update.execute(false, false);

    SchemaExport export = new SchemaExport(serviceRegistry, cfg);
    export.setDelimiter(";");
    export.setOutputFile("target/db/migration/create.sql");
    export.execute(false, false, false, true);     
}
项目:bygle-ldp    文件:HibernateListenersConfigurer.java   
@PostConstruct
public void registerListeners() {
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(dbEventInsertListener);
    registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(dbEventUpdateListener);
    registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(dbEventDeleteListener);
}
项目:AgileAlligators    文件:HibernateEventListenerWiring.java   
@PostConstruct
public void registerListeners()
{
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry()
        .getService( EventListenerRegistry.class );

    registry.getEventListenerGroup( EventType.PRE_COLLECTION_UPDATE ).appendListener( preCollectionUpdateEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_UPDATE ).appendListener( postUpdateEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ).appendListener( postInsertEventListener );
    registry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ).appendListener( postDeleteEventListener );
}
项目:high-performance-java-persistence    文件:ResultSetLimitTest.java   
@Test
public void testLimit() {
    final RowSelection rowSelection = new RowSelection();
    rowSelection.setMaxRows(getMaxRows());
    LimitHandler limitHandler = ((SessionFactoryImpl) sessionFactory()).getDialect().getLimitHandler();
    String limitStatement = limitHandler.processSql(SELECT_POST_COMMENT, rowSelection);
    long startNanos = System.nanoTime();
    doInJDBC(connection -> {
        try (PreparedStatement statement = connection.prepareStatement(limitStatement)) {
            limitHandler.bindLimitParametersAtEndOfQuery(rowSelection, statement, 1);
            statement.setInt(1, getMaxRows());
            statement.execute();
            int count = 0;
            ResultSet resultSet = statement.getResultSet();
            while (resultSet.next()) {
                resultSet.getLong(1);
                count++;
            }
            assertEquals(getMaxRows(), count);
        } catch (SQLException e) {
            fail(e.getMessage());
        }

    });
    LOGGER.info("{} Result Set with limit took {} millis",
            dataSourceProvider().database(),
            TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos));
}
项目:yawl    文件:YPersistenceManager.java   
public void closeFactory() {                    // shutdown persistence engine
    if (factory != null) {
        if (factory instanceof SessionFactoryImpl) {
           SessionFactoryImpl sf = (SessionFactoryImpl) factory;
           ConnectionProvider conn = sf.getConnectionProvider();
           if (conn instanceof C3P0ConnectionProvider) {
             ((C3P0ConnectionProvider)conn).stop();
           }
        }

        factory.close();
    }
}
项目:yawl    文件:HibernateEngine.java   
public void closeFactory() {
    if (_factory != null) {
        if (_factory instanceof SessionFactoryImpl) {
           SessionFactoryImpl sf = (SessionFactoryImpl) _factory;
           ConnectionProvider conn = sf.getConnectionProvider();
           if (conn instanceof C3P0ConnectionProvider) {
             ((C3P0ConnectionProvider)conn).stop();
           }
        }

        _factory.close();
    }
}
项目:stepic_java_webserver    文件:DBService.java   
public void printConnectInfo() {
    try {
        SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
        Connection connection = sessionFactoryImpl.getConnectionProvider().getConnection();
        System.out.println("DB name: " + connection.getMetaData().getDatabaseProductName());
        System.out.println("DB version: " + connection.getMetaData().getDatabaseProductVersion());
        System.out.println("Driver: " + connection.getMetaData().getDriverName());
        System.out.println("Autocommit: " + connection.getAutoCommit());
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
项目:spring-entity-listener    文件:HibernateEntityListenersAdapter.java   
@PostConstruct
public void findMethods() {
    for (Object listener : listeners) {
        findMethodsForListener(listener);
    }

    HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) emf;
    SessionFactory sf = hemf.getSessionFactory();
    registry = ((SessionFactoryImpl) sf).getServiceRegistry().getService(EventListenerRegistry.class);
}
项目:spring-entity-listener    文件:HibernateEntityListenersConfigurer.java   
@PostConstruct
public void registerListeners() {
    HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) emf;
    SessionFactory sf = hemf.getSessionFactory();
    EventListenerRegistry registry = ((SessionFactoryImpl) sf).getServiceRegistry().getService(
            EventListenerRegistry.class);

    registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(listener);
    registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(listener);
    registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(listener);
    registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(listener);
}
项目:snakerflow    文件:Hibernate4Access.java   
/**
 * 取得hibernate的connection对象
 */
protected Connection getConnection() throws SQLException {
    if (sessionFactory instanceof SessionFactoryImpl) {
        SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
        ConnectionProvider provider = sessionFactoryImpl.getServiceRegistry().getService(ConnectionProvider.class);
        if(provider != null) return provider.getConnection();
    }
    return null;
}
项目:Hibernate-Search-GenericJPA    文件:HibernateSynchronizedUpdateSourceProvider.java   
@Override
public SynchronizedUpdateSource getUpdateSource(
        ExtendedSearchIntegrator searchIntegrator,
        Map<Class<?>, RehashedTypeMetadata> rehashedTypeMetadataPerIndexRoot,
        Map<Class<?>, List<Class<?>>> containedInIndexOf,
        Properties properties,
        EntityManagerFactory emf,
        TransactionManager transactionManager,
        Set<Class<?>> indexRelevantEntities) {
    HibernateEntityManagerFactory hibernateEntityManagerFactory =
            (HibernateEntityManagerFactory) emf;
    SessionFactoryImpl sessionFactory = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
    ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
    EventListenerRegistry listenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );

    HibernateUpdateSource updateSource = new HibernateUpdateSource();
    updateSource.initialize( searchIntegrator );

    listenerRegistry.addDuplicationStrategy( new DuplicationStrategyImpl( HibernateUpdateSource.class ) );

    listenerRegistry.appendListeners( EventType.POST_INSERT, updateSource );
    listenerRegistry.appendListeners( EventType.POST_UPDATE, updateSource );
    listenerRegistry.appendListeners( EventType.POST_DELETE, updateSource );
    listenerRegistry.appendListeners( EventType.POST_COLLECTION_RECREATE, updateSource );
    listenerRegistry.appendListeners( EventType.POST_COLLECTION_REMOVE, updateSource );
    listenerRegistry.appendListeners( EventType.POST_COLLECTION_UPDATE, updateSource );

    return updateSource;
}
项目:HotswapAgent    文件:SessionFactoryProxy.java   
public SessionFactory proxy(SessionFactory sessionFactory, ServiceRegistry serviceRegistry) {
    this.currentInstance = sessionFactory;
    this.serviceRegistry = serviceRegistry;

    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(SessionFactoryImpl.class);
    factory.setInterfaces(new Class[]{SessionFactory.class});

    MethodHandler handler = new MethodHandler() {
        @Override
        public Object invoke(Object self, Method overridden, Method forwarder,
                             Object[] args) throws Throwable {
            return overridden.invoke(currentInstance, args);
        }
    };


    Object instance;
    try {
        Constructor constructor = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(factory.createClass(), Object.class.getDeclaredConstructor(new Class[0]));
        instance = constructor.newInstance();
        ((Proxy) instance).setHandler(handler);
    } catch (Exception e) {
        throw new Error("Unable instantiate SessionFactory proxy", e);
    }

    return (SessionFactory) instance;
}
项目:esup-dematec    文件:IndexController.java   
private String getHbm2ddlAuto() {
    Session session = entityManager.unwrap(Session.class);
    SessionFactoryImpl sessionImpl = (SessionFactoryImpl)session.getSessionFactory();
    Settings setting = sessionImpl.getSettings();
    String hbm2ddlAuto = setting.isAutoCreateSchema() ? "create" : "update";
    return hbm2ddlAuto;
}
项目:searchisko    文件:CdiHelper.java   
/**
     * Get Default DataSource. JNDI name of datasource is taken from Entity Manager
     *
     * @return
     * @throws NamingException
     */
    public static DataSource getDefaultDataSource(EntityManager em) throws NamingException {
//      Doesn't work because of https://hibernate.atlassian.net/browse/HHH-8121
//      EntityManagerFactory emFactory = em.getEntityManagerFactory();
//      Object ds = emFactory.getProperties().get("javax.persistence.jtaDataSource");
//      InitialContext initialContext = new InitialContext();
//      Object lookup = initialContext.lookup(ds.toString());
//      return (DataSource) lookup;

//      TODO: Find better way how to get DataSource from JPA without using hard coded JNDI name or casting to JPA implementation
        SessionFactoryImpl factory = (SessionFactoryImpl) em.unwrap(Session.class).getSessionFactory(); // or directly cast the sessionFactory
        DatasourceConnectionProviderImpl provider = (DatasourceConnectionProviderImpl) factory.getConnectionProvider();
        return provider.getDataSource();
    }
项目:lams    文件:SessionFactoryBuilderImpl.java   
@Override
public SessionFactory build() {
    return new SessionFactoryImpl(metadata, options, null );
}
项目:rpb    文件:HibernateListenerRegistration.java   
private <T> void register(EventType<T> eventType, T t) {
    EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
    log.info("Registering " + t.getClass() + " listener on " + eventType + " events.");
    registry.getEventListenerGroup(eventType).appendListener(t);
}
项目:engerek    文件:OrgClosureManager.java   
private boolean autoUpdateClosureTableStructure() {

        if (baseHelper.getConfiguration().isSkipOrgClosureStructureCheck()) {
            LOGGER.debug("Skipping org closure structure check.");
            return false;
        }

        SessionFactory sf = baseHelper.getSessionFactory();
        if (sf instanceof SessionFactoryImpl) {
            SessionFactoryImpl sfi = ((SessionFactoryImpl) sf);
            LOGGER.debug("SessionFactoryImpl.getSettings() = {}; auto update schema = {}", sfi.getSettings(), sfi.getSettings() != null ? sfi.getSettings().isAutoUpdateSchema() : null);
            if (sfi.getSettings() != null && sfi.getSettings().isAutoUpdateSchema()) {

                LOGGER.info("Checking the closure table structure.");

                final Session session = baseHelper.getSessionFactory().openSession();
                final Holder<Boolean> wrongNumberOfColumns = new Holder<>(false);
                session.doWork(new Work() {
                    @Override
                    public void execute(Connection connection) throws SQLException {
                        DatabaseMetaData meta = connection.getMetaData();
                        if (meta == null) {
                            LOGGER.warn("No database metadata found.");
                        } else {
                            ResultSet rsColumns = meta.getColumns(null, null, CLOSURE_TABLE_NAME, null);
                            int columns = 0;
                            while (rsColumns.next()) {
                                LOGGER.debug("Column: {} {}", rsColumns.getString("TYPE_NAME"), rsColumns.getString("COLUMN_NAME"));
                                columns++;
                            }
                            if (columns > 0) {
                                LOGGER.debug("There are {} columns in {} (obtained via DatabaseMetaData)", columns, CLOSURE_TABLE_NAME);
                                if (columns != 3) {
                                    wrongNumberOfColumns.setValue(true);
                                }
                                return;
                            }
                            // perhaps some problem here... let's try another way out
                            try {
                                Statement stmt = connection.createStatement();
                                ResultSet rs = stmt.executeQuery("select * from " + CLOSURE_TABLE_NAME);
                                int cols = rs.getMetaData().getColumnCount();
                                if (cols > 0) {
                                    LOGGER.debug("There are {} columns in {} (obtained via resultSet.getMetaData())", cols, CLOSURE_TABLE_NAME);
                                    if (cols != 3) {
                                        wrongNumberOfColumns.setValue(true);
                                    }
                                } else {
                                    LOGGER.warn("Couldn't determine the number of columns in {}. In case of problems, please fix your database structure manually using DB scripts in 'config' folder.", CLOSURE_TABLE_NAME);
                                }
                                rs.close();     // don't care about closing them in case of failure
                                stmt.close();
                            } catch (RuntimeException e) {
                                LoggingUtils.logException(LOGGER, "Couldn't obtain the number of columns in {}. In case of problems running midPoint, please fix your database structure manually using DB scripts in 'config' folder.", e, CLOSURE_TABLE_NAME);
                            }
                        }
                    }
                });
                if (wrongNumberOfColumns.getValue()) {
                    session.getTransaction().begin();
                    LOGGER.info("Wrong number of columns detected; dropping table " + CLOSURE_TABLE_NAME);
                    Query q = session.createSQLQuery("drop table " + CLOSURE_TABLE_NAME);
                    q.executeUpdate();
                    session.getTransaction().commit();

                    LOGGER.info("Calling hibernate hbm2ddl SchemaUpdate tool to create the table in the necessary form.");
                    new SchemaUpdate(sfi.getServiceRegistry(), baseHelper.getSessionFactoryBean().getConfiguration()).execute(false, true);
                    LOGGER.info("Done, table was (hopefully) created. If not, please fix your database structure manually using DB scripts in 'config' folder.");
                    return true;
                }
            } else {
                // auto schema update is disabled
            }
        } else {
            LOGGER.warn("SessionFactory is not of type SessionFactoryImpl; it is {}", sf != null ? sf.getClass() : "null");
        }
        return false;
    }
项目:engerek    文件:SqlRepositoryServiceImpl.java   
private void readDetailsFromConnection(RepositoryDiag diag, final SqlRepositoryConfiguration config) {
     final List<LabeledString> details = diag.getAdditionalDetails();

     Session session = baseHelper.getSessionFactory().openSession();
     try {
         session.beginTransaction();
         session.doWork(new Work() {

             @Override
             public void execute(Connection connection) throws SQLException {
                 details.add(new LabeledString(DETAILS_TRANSACTION_ISOLATION,
                         getTransactionIsolation(connection, config)));


                 Properties info = connection.getClientInfo();
                 if (info == null) {
                     return;
                 }

                 for (String name : info.stringPropertyNames()) {
                     details.add(new LabeledString(DETAILS_CLIENT_INFO + name, info.getProperty(name)));
                 }
             }
         });
         session.getTransaction().commit();

SessionFactory sessionFactory = baseHelper.getSessionFactory();
         if (!(sessionFactory instanceof SessionFactoryImpl)) {
             return;
         }
         SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
         // we try to override configuration which was read from sql repo configuration with
         // real configuration from session factory
         String dialect = sessionFactoryImpl.getDialect() != null ? sessionFactoryImpl.getDialect().getClass().getName() : null;
         details.add(new LabeledString(DETAILS_HIBERNATE_DIALECT, dialect));
     } catch (Throwable th) {
         //nowhere to report error (no operation result available)
         session.getTransaction().rollback();
     } finally {
         baseHelper.cleanupSessionAndResult(session, null);
     }
 }
项目:singular-server    文件:HealthSystemDAO.java   
@Transactional
public String getHibernateDialect(){
    return ((SessionFactoryImpl)sessionFactory).getDialect().toString();
}