我试图了解是否可以在session
之间共享休眠threads
并尝试编写如下代码:
想法如下。看看下面的代码中的execute
方法。
session
并启动transaction
session
用于任何数据库操作。但是,他们可以从sessionFactory
获取新会话,并将其用于任何特定操作。但是我不确定,Session
的其他任何方法(API)都可能导致问题吗?
public class MyDaoHibernateImpl {
/**
* returns session
* @return
*/
protected Session getSession(){
return HibernateUtil.getSessionFactory().openSession();
}
private SessionFactory getSessionFactory(){
return HibernateUtil.getSessionFactory();
}
private volatile Session session;
//This is not required to share across the threads
private volatile Transaction tx;
/**
* starting session and transaction
*/
public void openSession(){
session = getSession();
tx = session.beginTransaction();
}
/**
* commits unit of work
*/
public void commitSession(){
tx.commit();
session.flush();
session.close();
}
/**
* Rollback unit of work
*/
public void rollbackSession(){
tx.rollback();
session.flush();
session.close();
}
/**
* This method is just a template, it starts session and commits the session or rollback if any failure.
*/
public void execute(){
try{
openSession();
performOperationInsideAThread1();
performOperationInsideAThread2();
commitSession();
}catch (Exception e){
rollbackSession();
}
}
/**
* DO NOT COMMIT OR CLOSE THE SESSION HERE, However you are free to open new session and perform transactions.
* using getSessionFactory{@link #openSession()}
* @throws RuntimeException
*/
private void performOperationInsideAThread1() throws RuntimeException{
}
/**
* DO NOT COMMIT OR CLOSE THE SESSION HERE, However you are free to open new session and perform transactions.
* using getSessionFactory{@link #openSession()}
* @throws RuntimeException
*/
private void performOperationInsideAThread2() throws RuntimeException{
}
}