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

newbie picture newbie · Dec 10, 2010 · Viewed 59k times · Source

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 how can I set my datasource to my SessionFactory?

Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
configuration.setProperties(properties);
configuration.setProperty("packagesToScan", "com.my.app");
SessionFactory sessionFactory = configuration.configure().buildSessionFactory();

Answer

dira picture dira · Dec 10, 2010

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);