Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

Programmatically provide datasource to hibernate

I would like to know if it is possible to programmatically provide a DataSource object to hibernate configuration?
In our system we construct a datasource object (this is a Java SE application), and I would like to move from plain JDBC code to hibernate.
If someone knows the answer with JPA this is also fine.

Upvotes: 3

Views: 4462

Answers (2)

Allan Veloso
Allan Veloso

Reputation: 6369

Yes, it's possible. You will just need to implement a PersistenceUnitInfo:

public class PersistenceOptions implements PersistenceUnitInfo {

    private DataSource jtaDataSource;

    void setJtaDataSource(DataSource jtaDataSource){
        this.jtaDataSource = jtaDataSource;
    }

    @Override
    public DataSource getNonJtaDataSource() {
        return jtaDataSource;
    }

    // ... You will have to implement a bunch of other methods that are used 
    // by Hibernate configuration, like getProperties()
}

Usage:

PersistenceOptions options = new PersistenceOptions();
DataSource myFancyDataSource = new BasicDataSource();
options.setJtaDataSource(myFancyDataSource);
EntityManagerFactory emf = new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(options), null
).build();
EntityManager em = emf.createEntityManager();

Upvotes: 0

helderdarocha
helderdarocha

Reputation: 23637

You can use a org.hibernate.cfg.Configuration object.

For example - a datasource:

Configuration cfg = new Configuration()
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
    .setProperty("hibernate.connection.datasource", "java:/MySQLDS");

or a driver manager:

Configuration cfg = new Configuration()
    .setProperty("hibernate.connection.driver_class", "org.postgresql.Driver")
    .setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/test")
    .setProperty("hibernate.connection.username", "user")
    .setProperty("hibernate.connection.username", "pass");

See: Hibernate Programmatic Configuration

Upvotes: 4

Related Questions