1

I would like to get a datasource from a hibernate Configuration programmaticaly. Here is the code that I wrote :

public static DataSource getDatasource(Configuration configuration){
    ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    SessionFactoryImpl session = (SessionFactoryImpl)configuration.buildSessionFactory(registry);
    DatasourceConnectionProviderImpl provider = (DatasourceConnectionProviderImpl) session.getConnectionProvider();
    return provider.getDataSource();
}

But I got an exception while running the application :

Exception in thread "main" org.hibernate.HibernateException: Missing table: CONTACTS
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1281)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:508)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1769)
at com.heavenize.Migrations.getDatasource(Migrations.java:30)
at com.heavenize.Migrations.main(Migrations.java:60)

I am performing some database migration and I need the datasource to pass to my migration tool programmaticaly.

It seems that problem come with the fact that buildSessionFactory because hibernate is trying to map the entities with the tables in the database.

The property "hibernate.hbm2ddl.auto" is set to validate.

Is there a better way to get the datasource?

Dimitri
  • 8,122
  • 19
  • 71
  • 128
  • You are right that it is an issue with Hibernate initialization due to `hbm2ddl`, even without your code you would get it. Read the documentation and find the value that does not create neither update neither validate the ddl. – SJuan76 Jun 18 '13 at 13:56

1 Answers1

1

The error that you are getting has nothing to do with retrieving the DataSource. It is because Hibernate is validating the data model with the database and doesn't find it to be in syncrhonization. You can remove the hibernate.hbm2ddl.auto property completely, which will then default it to none and there won't be any validation.

Mubin
  • 4,192
  • 3
  • 26
  • 45