HIbernate 非Spring托管事务处理

public <T> void saveforThread(T entity) {
        SessionFactory sessionFactory = this.getSessionFactory();
        Session session = sessionFactory.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        try {
            session.save(entity);
            tx.commit();
        } catch (RuntimeException exception) {
            tx.rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

  需要自己新建一个session,开启事务处理。

  实验网上找到的解决方案:

TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));

失败了,事务不起作用,执行save后不能写入库。不知道是什么原因。

posted @ 2017-06-08 10:03  sdlt  阅读(205)  评论(0编辑  收藏  举报