Search in sources :

Example 1 with UnknownServiceException

use of org.hibernate.service.UnknownServiceException in project spring-framework by spring-projects.

the class SessionFactoryUtils method getDataSource.

/**
	 * Determine the DataSource of the given SessionFactory.
	 * @param sessionFactory the SessionFactory to check
	 * @return the DataSource, or {@code null} if none found
	 * @see ConnectionProvider
	 */
public static DataSource getDataSource(SessionFactory sessionFactory) {
    Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
    if (getProperties != null) {
        Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
        Object dataSourceValue = props.get(Environment.DATASOURCE);
        if (dataSourceValue instanceof DataSource) {
            return (DataSource) dataSourceValue;
        }
    }
    if (sessionFactory instanceof SessionFactoryImplementor) {
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
        try {
            ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
            if (cp != null) {
                return cp.unwrap(DataSource.class);
            }
        } catch (UnknownServiceException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
            }
        }
    }
    return null;
}
Also used : SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) UnknownServiceException(org.hibernate.service.UnknownServiceException) Method(java.lang.reflect.Method) Map(java.util.Map) DataSource(javax.sql.DataSource) ConnectionProvider(org.hibernate.engine.jdbc.connections.spi.ConnectionProvider)

Aggregations

Method (java.lang.reflect.Method)1 Map (java.util.Map)1 DataSource (javax.sql.DataSource)1 ConnectionProvider (org.hibernate.engine.jdbc.connections.spi.ConnectionProvider)1 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)1 UnknownServiceException (org.hibernate.service.UnknownServiceException)1