epbernard wrote:
Open 2 session factories with 2 different Configuration
2-PC exists in Hibernate if your transaction manager manage it. hibernate always delegate Transaction to etiher:
- JDBC
- JTA
Yeah, I have used 2 session factory and 2 different configuration. Look:
Code:
public void configureTwoPhaseCommit() throws HibernateException {
Configuration cfg = new Configuration();
Configuration cfg2 = new Configuration();
cfg.configure("/hibernate.cfg.xml");
cfg2.configure("/hibernatebkp.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
sessionFactory2 = cfg2.buildSessionFactory();
}
So, I use them here:
Code:
public Blog createBlog(String name) throws HibernateException{
Blog blog = new Blog();
blog.setName(name);
blog.setItems( new ArrayList() );
Session session = sessionFactory.openSession();
Session sessionBackup = sessionFactory2.openSession();
Transaction tx = null;
Transaction tx2 = null;
try {
tx = session.beginTransaction();
tx2 = sessionBackup.beginTransaction();
[b]session.save(blog);[/b]
[b]sessionBackup.save(blog);[/b]
/*
Blog bbkp = new Blog();
BeanUtils.copyProperties(bbkp, blog);
sessionBackup.save(bbkp);
*/
tx.commit();
tx2.commit();
log.info("Blog '" + name + "' persistido");
} catch(JDBCException e){
if (e.getErrorCode() == 1062){
System.out.println("Ja existe um blog com esse nome no banco, escolha outro");
}
} catch (HibernateException he) {
if (tx != null) tx.rollback();
if (tx2 != null) tx2.rollback();
throw he;
} finally {
session.close();
sessionBackup.close();
}
return blog;
}
session.save(blog) works fine, but sessionbkp.save(blog) throws the following exception:
Code:
Illegal attempt to associate a collection with two open sessions
Please help me !! And about transaction, am I writing the right code ?
Thank you !