TransactionRequiredException:消费者内的当前线程没有正在进行的事务

时间:2018-12-07 10:06:10

标签: java hibernate

我需要让使用者使用MyStuff对象的列表,但需要能够将其锁定在数据库级别,以便数据不会被多个服务器破坏。

@Service
@EnableTransactionManagement
public class Worker{
    @Autowired
    private SessionFactory sessionFactory;
    private Session getSession(){
        return sessionFactory.openSession();
    }

    private MyObject getMyObject(Session session, Long id){
        MyObject myObj = session.get(MyObject.class, id,LockMode.PESSIMISTIC_WRITE);
        session.refresh(myObj);
        return myObj;
    }

    @Transactional
    private Consumer<List<MyStuff>> getNewConsumer(){
        return new Consumer(){
            private void accept(List<MyStuff> myStuff){
                Session session = getSession();
                Long id = myStuff.getID();
                MyObject myObject = getMyObject(session, id);

                //process MyStuff
                session.save(myObject);
                session.flush();
                session.close();
            }
        }
    }
}

我收到异常消息:

  

javax.persistence.TransactionRequiredException:没有事务正在进行中>     在org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl.java:3461)     在org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1425)     在org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1421)     在com.me.Worker $ 1.save(Worker.java)

如何解决?

0 个答案:

没有答案