How can I set Datasource when I'm creating Hibernate SessionFactory?

后端 未结 8 406
星月不相逢
星月不相逢 2020-12-02 17:17

I\'m creating SessionFactory and I have my datasource as object in code where I\'m creating SessionFactory, but i cannot set datasource to Hibernate Configuration object. So

8条回答
  •  失恋的感觉
    2020-12-02 18:08

    To supply JDBC connections to Session, you need an implementation of ConnectionProvider.

    By default, Hibernate uses DatasourceConnectionProvider which obtains a DataSource instance from JNDI.

    To use a custom DataSource instance, use InjectedDataSourceConnectionProvider and inject the DataSource instance into it.

    There is TODO note on InjectedDataSourceConnectionProvider

    NOTE : setDataSource(javax.sql.DataSource) must be called prior to configure(java.util.Properties).

    TODO : could not find where setDataSource is actually called. Can't this just be passed in to configure???

    As per the note, call setDataSource() method from configure() method.

    public class CustomConnectionProvider extends InjectedDataSourceConnectionProvider {
        @Override
        public void configure(Properties props) throws HibernateException {
            org.apache.commons.dbcp.BasicDataSource dataSource = new BasicDataSource();
            org.apache.commons.beanutils.BeanUtils.populate( dataSource, props );
            setDataSource(dataSource);
    
            super.configure(props);
        }
    }
    

    You can also extend UserSuppliedConnectionProvider.

    According to the contract of ConnectionProvider

    Implementors should provide a public default constructor.

    Hibernate will invoke this constructor if custom ConnectionProvider is set through Configuration instance.

    Configuration cfg = new Configuration();
    Properties props = new Properties();
    props.put( Environment.CONNECTION_PROVIDER, InjectedDataSourceConnectionProvider.class.getName() );
    cfg.addProperties(props);
    

提交回复
热议问题