2

Well, I'm working on an application which syncs two databases. I need to setup hibernate.cfg.xml for 2 databases. Postgresql and Firebird. I'd like to create a generic class to set up my hibernate.cfg.xml.

I'd like to do something like this:

currentSessionFactory = new AnnotationConfiguration()
.setProperty("hibernate.dialect", entity.getDialect())
.setProperty("hibernate.connection.driver_class", entity.getDriverClass())

I need a new hibernate.cfg.xml for the second database but I can't set up it via xml, I need to do it through Java code.

How should I do it ?

1 Answer 1

3

You can use Hibernate Configuration class to replace the hibernate.cfg.xml alltogether:

Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Entity1.class);
ServiceRegistry serviceRegistry
            = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();            
sessionFactory = configuration.buildSessionFactory(serviceRegistry);

The Configuration class allows you to:

  • add classes
  • add properties

Here you have an example on GitHub.

Sign up to request clarification or add additional context in comments.

3 Comments

Well, this setup is for the HibernateUtil class, I want to build a class to setup the hibernate xml file, without using xml.
Then you can use the Configuration class to replace the whole hibernate.cfg.xml. Check my updated answer.
Thank you :D you did a nice job \o/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.