Hi,
You'll have to write your own ConnectionProvider, like below :
Code:
public class MyOwnDatasourceConnectionProvider implements ConnectionProvider
{
private DataSource dataSource;
public void configure(Properties arg0) throws HibernateException {
}
public Connection getConnection() throws SQLException {
return this.getDataSource().getConnection();
}
public void closeConnection(Connection arg0) throws SQLException {
if(this.getConnection() != null) this.getConnection().close();
}
public void close() throws HibernateException {
}
public boolean supportsAggressiveRelease() {
return true;
}
public DataSource getDataSource()
{
if(this.dataSource == null)
{
this.dataSource = //... here your code that returns your own DataSource instance
}
return this.dataSource;
}
}
and define your ConnectionProvider in Hibernate's configuration. For example, in HibernateUtil :
Code:
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
// Define my own ConnectionProvider (watch out connection parameters from hibernate.cfg.xml will no longer be used)
configuration.setProperty(Environment.CONNECTION_PROVIDER, MyOwnDatasourceConnectionProvider.class.getName());
sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}