Hibernation is a problem

I have a problem.

My app is using 1) existing hibernate to get some data. Now I need to 2) update some tables in the same DB that the data is being fetched from, and this should happen through a separate connection.

Is it possible to use the hibernate.cfg.xml file separately for this?

if so, how will I distinguish the connections.

Or I can't hibernate for the second case?

kind help.

+1


a source to share


2 answers


Without testing this scenario, it should be possible with Hibernate. You need to set up two SessionFactorys using the same mapping but different configurations for connection ( -> hibernate.cfg.xml

). In the application, the 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 is also a method to open a session with a given JDBC connection (see JavaDoc for SessionFactory ), but I've never used that. Perhaps you could try. The first solution looks cleaner to me.

0


a source


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

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 this, then just get the session from the correct factory session.

0


a source







All Articles