data persistence in two or more databases simultaneously

Asked

Viewed 79 times

1

Greetings!

I would like someone to help me with some example of a JSF application that persists data simultaneously in more than one database, that is: will connect there are 2+ databases and will inject data in these.

I’m using Hibernate.

The project is in: https://github.com/felippefloriani/buildsoft

Thank you!

1 answer

2

Yeah, I got!

If anyone is with the same doubt, I will share here my solution:

  1. Besides Hibernate.cfg.xml, I created another file that I called hibernate1.cfg.xml in which I include the sessionfactory of the other database. NOTE: In my project, the first Hibernate.cfg.xml is for Mysql and, the second, for Postgresql.

  2. In the package br.com.meuprojeto.util I already had the class Hibernateutil.java. So I created another class, this time Hibernateutil1.java whose implementation follows:

import org.hibernate.Sessionfactory; import org.hibernate.boot.registry.Standardserviceregistrybuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.Serviceregistry;

public class Hibernateutil1 {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {

    try {
        // Cria SessionFactory a partir do hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure("hibernate1.cfg.xml").buildSessionFactory();

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;

    } catch (Throwable ex) {
        System.err.println("Falha ao tentar criar o SessionFactory." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

  1. Within my package br.com.meuprojeto.main, I have the class Geratable.java with the main method calling the two classes Hibernateutil and Hibernateutil1, as follows:

public class Geratabela {

public static void main(String[] args) {
    HibernateUtil.getSessionFactory();
    HibernateUtil.getSessionFactory().close();

    HibernateUtil1.getSessionFactory();
    HibernateUtil1.getSessionFactory().close();

}

}

It may not be the most elegant solution. But I ran this class and there were the tables created in both banks.

Thanks to those who accompanied!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.