Q:

Hibernate using an instance of javax.sql.DataSource

Is it possible to configure Hibernate to use a javax.sql.DataSource instance?
My application already has an instance of javax.sql.DataSource and I'd rather not re-configure the database url, user, password, driver etc just for hibernate.

A:

In your hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>    
        <property name="connection.datasource">SampleDS</property>        
    </session-factory>

</hibernate-configuration>

A:

If the data source is available through JNDI, you just need to set the hibernate.connection.datasource property of the configuration - mtpettyp's answer demonstrates that.
If you're not in an environment where your data sources come from JNDI, provide your own ConnectionProvider implementation, and either pass it to the Settings object before building the session factory, or specify its class name in the hibernate.connection.provider_class property. If you provide an instance to Settings, you can probably instantiate the standard DatasourceConnectionProvider and give it your DataSource.

