views:

558

answers:

3

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.

+3  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"&gt;

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

</hibernate-configuration>
mtpettyp
+1  A: 

If you're using spring initialization and a spring session factory bean you can simply pass in the data source like this

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    ...
</bean>

where the dataSource reference is defined elsewhere.

Jherico
+3  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.

araqnid