org.hibernate.internal.SessionFactoryImpl Java Examples

The following examples show how to use org.hibernate.internal.SessionFactoryImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: mycore   Author: MyCoRe-Org   File: MCRHibernateConfigHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
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,
                    String.format(Locale.ROOT, "add constraint %s unique (%s) 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);
            }
        });
    }
}
 
Example #2
Source Project: unitime   Author: UniTime   File: HibernateUtil.java    License: Apache License 2.0 6 votes vote down vote up
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;
	}
}
 
Example #3
@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;
		}
	});

}
 
Example #4
Source Project: base-framework   Author: biliroy   File: BasicHibernateDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据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;
}
 
Example #5
Source Project: base-framework   Author: biliroy   File: BasicHibernateDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据查询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);
}
 
Example #6
Source Project: hibernate-reactive   Author: hibernate   File: MutinySessionFactoryImpl.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Mutiny.Session createSession() {
	ReactiveConnectionPool pool = delegate.getServiceRegistry()
			.getService(ReactiveConnectionPool.class);
	return new MutinySessionImpl(
			new ReactiveSessionImpl(
					delegate,
					new SessionFactoryImpl.SessionBuilderImpl<>(delegate),
					pool.getProxyConnection()
			)
	);
}
 
Example #7
Source Project: hibernate-reactive   Author: hibernate   File: MutinySessionFactoryImpl.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Uni<Mutiny.Session> openSession() throws HibernateException {
	ReactiveConnectionPool pool = delegate.getServiceRegistry()
			.getService(ReactiveConnectionPool.class);
	return Uni.createFrom().completionStage( pool.getConnection() )
			.map( reactiveConnection -> new ReactiveSessionImpl(
					delegate,
					new SessionFactoryImpl.SessionBuilderImpl<>(delegate),
					reactiveConnection
			) )
			.map( MutinySessionImpl::new );
}
 
Example #8
Source Project: hibernate-reactive   Author: hibernate   File: StageSessionFactoryImpl.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Stage.Session createSession() {
	ReactiveConnectionPool pool = delegate.getServiceRegistry()
			.getService(ReactiveConnectionPool.class);
	return new StageSessionImpl(
			new ReactiveSessionImpl(
					delegate,
					new SessionFactoryImpl.SessionBuilderImpl<>(delegate),
					pool.getProxyConnection()
			)
	);
}
 
Example #9
Source Project: hibernate-reactive   Author: hibernate   File: StageSessionFactoryImpl.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public CompletionStage<Stage.Session> openSession() throws HibernateException {
	ReactiveConnectionPool pool = delegate.getServiceRegistry()
			.getService(ReactiveConnectionPool.class);
	return pool.getConnection()
			.thenApply( reactiveConnection -> new ReactiveSessionImpl(
					delegate,
					new SessionFactoryImpl.SessionBuilderImpl<>(delegate),
					reactiveConnection
			) )
			.thenApply( StageSessionImpl::new );
}
 
Example #10
Source Project: quarkus   Author: quarkusio   File: FastBootEntityManagerFactoryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public EntityManagerFactory build() {
    try {
        final SessionFactoryOptionsBuilder optionsBuilder = metadata.buildSessionFactoryOptionsBuilder();
        populate(optionsBuilder, standardServiceRegistry, multiTenancyStrategy);
        return new SessionFactoryImpl(metadata.getOriginalMetadata(), optionsBuilder.buildOptions(), HQLQueryPlan::new);
    } catch (Exception e) {
        throw persistenceException("Unable to build Hibernate SessionFactory", e);
    }
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: NamedProcedureCallDefinition.java    License: GNU General Public License v2.0 5 votes vote down vote up
public List<ParameterMemento> toMementos(SessionFactoryImpl sessionFactory) {
	final List<ParameterMemento> mementos = new ArrayList<ParameterMemento>();
	for ( ParameterDefinition definition : parameterDefinitions ) {
		mementos.add(definition.toMemento( sessionFactory ));
	}
	return mementos;
}
 
Example #12
Source Project: lams   Author: lamsfoundation   File: NamedProcedureCallDefinition.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("UnnecessaryUnboxing")
public ParameterMemento toMemento(SessionFactoryImpl sessionFactory) {
	final boolean initialPassNullSetting = explicitPassNullSetting != null
			? explicitPassNullSetting.booleanValue()
			: sessionFactory.getSessionFactoryOptions().isProcedureParameterNullPassingEnabled();

	return new ParameterMemento(
			position,
			name,
			parameterMode,
			type,
			sessionFactory.getTypeResolver().heuristicType( type.getName() ),
			initialPassNullSetting
	);
}
 
Example #13
Source Project: lams   Author: lamsfoundation   File: MetadataImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public NamedQueryRepository buildNamedQueryRepository(SessionFactoryImpl sessionFactory) {
	return new NamedQueryRepository(
			namedQueryMap,
			namedNativeQueryMap,
			sqlResultSetMappingMap,
			buildProcedureCallMementos( sessionFactory )
	);

}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: MetadataImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Map<String, ProcedureCallMemento> buildProcedureCallMementos(SessionFactoryImpl sessionFactory) {
	final Map<String, ProcedureCallMemento> rtn = new HashMap<>();
	if ( namedProcedureCallMap != null ) {
		for ( NamedProcedureCallDefinition procedureCallDefinition : namedProcedureCallMap.values() ) {
			rtn.put(
					procedureCallDefinition.getRegisteredName(),
					procedureCallDefinition.toMemento( sessionFactory,sqlResultSetMappingMap )
			);
		}
	}
	return rtn;
}
 
Example #15
Source Project: jeesupport   Author: aiyoyoyo   File: SessionFactoryRegistry.java    License: MIT License 5 votes vote down vote up
public void registerSessionFactory(String _name) {
    AtomikosDataSourceBean ds = createXADataSource(_name);
    SessionFactoryImpl bean = createSessionFactoryBean( _name, ds );

    ISupportDao dao = CommonContextHolder.getBean(ISupportDao.class);
    dao.putSessionFactory( _name , bean );
}
 
Example #16
Source Project: jeesupport   Author: aiyoyoyo   File: SessionFactoryRegistry.java    License: MIT License 5 votes vote down vote up
private SessionFactoryImpl createSessionFactoryBean( String _name, AtomikosDataSourceBean _ds ) {
    String head = "jees.jdbs.config." + _name + ".";
    String hibernate = head + "hibernate.";
    String orm = CommonConfig.getString( head + "orm" );
    String bean = _name + "SessionFactory";

    BeanDefinitionBuilder beanDefinitionBuilder =
            BeanDefinitionBuilder.rootBeanDefinition(LocalSessionFactoryBean.class);

    if( orm.equalsIgnoreCase("hibernate") ){
        Properties hibernateProperties = new Properties();

        hibernateProperties.setProperty("hibernate.dialect",
                CommonConfig.getString( hibernate + "dialect","org.hibernate.dialect.MySQL55Dialect") );
        hibernateProperties.setProperty("hibernate.show_sql",
                CommonConfig.getString( hibernate + "showSql","true" ) );
        hibernateProperties.setProperty("hibernate.transaction.factory_class",
                CommonConfig.getString( hibernate + "factoryClass","org.hibernate.transaction.JTATransactionFactory" ) );
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto",
                CommonConfig.getString( hibernate + "hbm2ddl", "none" ) );
        hibernateProperties.setProperty("hibernate.transaction.jta.platform",
                CommonConfig.getString( hibernate + "platform", "com.jees.core.database.config.AtomikosJtaPlatform" ) );
        hibernateProperties.setProperty("hibernate.transaction.coordinator_class",
                CommonConfig.getString( hibernate + "coordinatorClass","jta" ) );

        beanDefinitionBuilder.addPropertyValue("dataSource", _ds);
        beanDefinitionBuilder.addPropertyValue("packagesToScan",
                CommonConfig.getString( head + "packagesToScan" ) );
        beanDefinitionBuilder.addPropertyValue("hibernateProperties", hibernateProperties);
    }

    ConfigurableApplicationContext context = (ConfigurableApplicationContext) CommonContextHolder.getApplicationContext();
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();

    log.debug("--创建LocalSessionFactoryBean[" + bean + "]。");

    beanFactory.registerBeanDefinition(bean, beanDefinitionBuilder.getBeanDefinition());

    return CommonContextHolder.getBean( bean );
}
 
Example #17
Source Project: mycore   Author: MyCoRe-Org   File: MCRHibernateConfigHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
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());
    }
}
 
Example #18
Source Project: mojito   Author: box   File: HibernateEventListenerConfig.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #19
@PostConstruct
protected void init()
{
    SessionFactoryImpl sessionFactory = emf.unwrap( SessionFactoryImpl.class );

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

    registry.getEventListenerGroup( EventType.POST_COMMIT_INSERT ).appendListener( insertEventListener );

    registry.getEventListenerGroup( EventType.POST_COMMIT_DELETE ).appendListener( deleteEventListener );
}
 
Example #20
Source Project: high-performance-java-persistence   Author: vladmihalcea   File: ResultSetLimitTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #21
Source Project: yawl   Author: yawlfoundation   File: YPersistenceManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example #22
Source Project: yawl   Author: yawlfoundation   File: HibernateEngine.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example #23
Source Project: stepic_java_webserver   Author: vitaly-chibrikov   File: DBService.java    License: MIT License 5 votes vote down vote up
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();
    }
}
 
Example #24
Source Project: snakerflow   Author: snakerflow   File: Hibernate4Access.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 取得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;
}
 
Example #25
Source Project: HotswapAgent   Author: HotswapProjects   File: SessionFactoryProxy.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #26
Source Project: keycloak   Author: keycloak   File: HibernateStatsReporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(KeycloakSession session) {
    SessionFactory sessionFactory = ((SessionFactoryImpl) emf);
    Statistics stats = sessionFactory.getStatistics();

    logStats(stats);

    stats.clear(); // For now, clear stats after each iteration
}
 
Example #27
Source Project: keycloak   Author: keycloak   File: QuarkusJpaConnectionProviderFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Connection getConnection() {
    SessionFactoryImpl entityManagerFactory = SessionFactoryImpl.class.cast(emf);

    try {
        return entityManagerFactory.getJdbcServices().getBootstrapJdbcConnectionAccess().obtainConnection();
    } catch (SQLException cause) {
        throw new RuntimeException("Failed to obtain JDBC connection", cause);
    }
}
 
Example #28
Source Project: hibernate-reactive   Author: hibernate   File: ReactiveSessionImpl.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public ReactiveSessionImpl(SessionFactoryImpl delegate, SessionCreationOptions options,
						   ReactiveConnection connection) {
	super( delegate, options );
	reactiveConnection = connection;
}
 
Example #29
public ReactiveCriteriaBuilderImpl(SessionFactoryImpl sessionFactory) {
	super(sessionFactory);
}
 
Example #30
Source Project: hibernate-reactive   Author: hibernate   File: MutinySessionFactoryImpl.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
public MutinySessionFactoryImpl(SessionFactoryImpl delegate) {
	this.delegate = delegate;
}