Question

I want to connect multiple databases like SQL and Oracle with different databases.So i already had MSSQL hibernate.cfg.xml and Hibernateutil class for session factory.Now i'm trying to connect oracle with different table.

Please advise can i use same cgf.xml and util class can configure oracle databases as well.

Here is util class.

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory()
    {
        try
        {

            SessionFactory sessionFactory = new Configuration().configure("/DAO/hibernate.cfg.xml").buildSessionFactory();
            return sessionFactory;        
        }
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}
Was it helpful?

Solution

You need to provide a cfg.xml for each database.

 Oracle.cfg.xml
 mssql.cfg.xml

There you provide the appropriate database connecton configuration, the dialect to use and which hbm-mapping files for the entity classes are needed

Within your code you create a single SessionFactory for each database.

SessionFactory oracleSF = Configuration.configure("oracle.cfg.xml").buildSessionFfactory();
SessionFactory msSF = Conf..configure("mssql.cfg.xml").build....

To reuse your util class you just have to pass the name of the config file to the method which creates the SessionFactory as an additional parameter.

The entity classes of the different tables are declared within the appropriate config file and therefore assigned to the right database, so hibernate knows which database to use.

Also take a look at this discussion which is about multiple schemas with a single cfg:

how to use Hibernate for two different schemas in a single database

Have a look here: It is a pretty nice site with an vast amount of tutorials for hibernate:

http://www.javabeat.net/hibernate/page/4/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top