如何在多个线程之间共享Hibernate Session

时间:2019-02-08 06:17:44

标签: java hibernate

我试图了解是否可以在session之间共享休眠threads并尝试编写如下代码:

想法如下。看看下面的代码中的execute方法。

  • 打开session并启动transaction
  • 启动各个线程。线程将session用于任何数据库操作。但是,他们可以从sessionFactory获取新会话,并将其用于任何特定操作。
  • 调用commit提交所有更改,否则,将执行回滚。

但是我不确定,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{

    }

}

0 个答案:

没有答案