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 File: MCRHibernateConfigHelper.java    From mycore with 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 File: HibernateUtil.java    From unitime with 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
Source File: ResourceLocalFlexyPoolHibernateConnectionProviderIntegrationTest.java    From flexy-pool with Apache License 2.0 6 votes vote down vote up
@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 File: BasicHibernateDao.java    From base-framework with 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 File: BasicHibernateDao.java    From base-framework with 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 File: MutinySessionFactoryImpl.java    From hibernate-reactive with 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 File: MutinySessionFactoryImpl.java    From hibernate-reactive with 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 File: StageSessionFactoryImpl.java    From hibernate-reactive with 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 File: StageSessionFactoryImpl.java    From hibernate-reactive with 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 File: FastBootEntityManagerFactoryBuilder.java    From quarkus with 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 File: NamedProcedureCallDefinition.java    From lams with 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 File: NamedProcedureCallDefinition.java    From lams with 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 File: MetadataImpl.java    From lams with 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 File: MetadataImpl.java    From lams with 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 File: SessionFactoryRegistry.java    From jeesupport with 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 File: SessionFactoryRegistry.java    From jeesupport with 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 File: MCRHibernateConfigHelper.java    From mycore with 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 File: HibernateEventListenerConfig.java    From mojito with 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
Source File: DeletedObjectListenerConfigurer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 File: ResultSetLimitTest.java    From high-performance-java-persistence with 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 File: YPersistenceManager.java    From yawl with 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 File: HibernateEngine.java    From yawl with 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 File: DBService.java    From stepic_java_webserver with 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 File: Hibernate4Access.java    From snakerflow with 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 File: SessionFactoryProxy.java    From HotswapAgent with 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 File: HibernateStatsReporter.java    From keycloak with 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 File: QuarkusJpaConnectionProviderFactory.java    From keycloak with 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 File: ReactiveSessionImpl.java    From hibernate-reactive with 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
Source File: ReactiveCriteriaBuilderImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ReactiveCriteriaBuilderImpl(SessionFactoryImpl sessionFactory) {
	super(sessionFactory);
}
 
Example #30
Source File: MutinySessionFactoryImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
public MutinySessionFactoryImpl(SessionFactoryImpl delegate) {
	this.delegate = delegate;
}