tags:

views:

66

answers:

2

I have a problem.

My application makes use 1) of an existing hibernate connection for retrieving some data. Now i t has to 2) update some tables in the same DB from which data is retrieved and this has to happen through seperate connection.

Is it possible to have a hibernate.cfg.xml file seperately for this purpose?

if so how will i differentiate between the connections.

Or i cant use hibernate itself for second case ?

kindly help.

A: 

Without having tested this scenario it should be possible with Hibernate. You need to set up two SessionFactorys using the same mapping but different configurations for the connection (-> hibernate.cfg.xml). In the application usage would look like

// read entry using first session factory
Session sessionForRead = readSessionFactory.getCurrentSession(); // or openSession()
sessionForRead.beginTransaction();
MyEntry entry = (MyEntry) sessionForRead.load(MyEntry.class, someId) // or whatever to load entries
sessionForRead.getTransaction().commit();

// update entry using the other session factory
Session sessionForUpdate = updateSessionFactpry.getCurrentSession(); // or openSession()
sessionForUpdate.beginTransaction();
sessionForUpdate.update(entry);
sessionForUpdate.getTransaction().commit();

There also exists a method to open a session with a given JDBC connection (see JavaDoc for SessionFactory), but I never used it. Perhaps you could give it a try. The first solution looks cleaner to me, though.

rudolfson
A: 

There are two ways to do this. You can explicitly pass the XML configuration file to the configuration:

AnnotationConfiguration cfg1 = new AnnotationConfiguration();
cfg.configure("/hibernate1.cfg.xml");

AnnotationConfiguration cfg2 = new AnnotationConfiguration();
cfg.configure("/hibernate2.cfg.xml");

Or you can manually update the database properties before getting the SessionFactory:

Configuration cfg1 = new Configuration();
cfg1.addClass(...)
Properties p = new Properties();
p.put(Environment.DATASOURCE, "jdbc/database1"); // if using JNDI
p.put(Environment.URL, DRIVER, etc..) // if using a direction connection
cfg1.addProperties(p);
cfg1.buildSessionFactory();

... repeat for other configurations using different properties

However you do it, you then just get the session from the correct session factory.

Brian Deterling