简体   繁体   English

休眠保存,休眠回滚

[英]Hibernate Save, Hibernate Rollback

I'm trying to make my DAO work this way: 我正在尝试以这种方式使我的DAO工作:

    public void incrementNumber(long id) throws Exception{
        Session session = factory.openSession();
        Number n = (Number)session.load(Number.class, id);
        n.setNumber(n.getNumber() +5);
//      throw new IllegalArgumentException("BLAH");
        session.close();
    }
  1. By commenting out the exception, the update will commit. 通过注释掉异常,将提交更新。
  2. By un-commenting(?) the exception, it will rollback. 通过取消注释(?)异常,它将回滚。

Any way to achieve this? 有什么办法可以做到这一点? Note: the transaction part is done in a service, under a transactional annotation. 注意:事务部分是在服务中的事务注释下完成的。

DAO is mainly responsible for persistence operations .It should only provide CRUD and some finder methods relating to a particular entity. DAO主要负责持久性操作。它仅应提供与特定实体有关的CRUD和一些查找器方法。

IMO , your method more like a business operation rather than the persistence operations . IMO,您的方法更像是业务操作而不是持久性操作。 As you have the service layer , I suggest you move this method to it. 当您拥有服务层时,建议您将这种方法移至该层。

So , your NumberDAO may look like this: 因此,您的NumberDAO可能如下所示:

public class NumberDAO {

     public Number loadById(long id){ }

}

And you NumberService may look like this: 您的NumberService可能看起来像这样:

public class NumberService{

        //Inject by DI containers , or setter / constructor
        NumberDAO numberDAO;

         public void incrementNumber(long id , int increaseAmount) throws Exception{

                Number n = (Number) numberDAO.loadById(id);

                if (XXXXXXXX) 
                    throws new IllegalArgumentException("BLAH BLAH BLAH BLAH");

                n.setNumber(n.getNumber() +increaseAmount);
         }

}

As you use transactional annotation in the service layer , it will commit automatically if your service method returns successfully .In case of any exceptions throw before the method returns , the transaction will rollback automatically . 在服务层中使用事务注释时,如果服务方法成功返回,它将自动提交。如果在方法返回之前引发任何异常,则事务将自动回滚。

commit is not always committing to the db, it is setting at the session cache that this has to be committed, then when you will do flush (also depending on the configuration) the commit will go to the DB, or when the session/transaction ends. commit并不总是提交给数据库,它是在会话缓存中设置必须提交的,然后当您进行刷新(也取决于配置)时,提交将进入数据库,或者会话/事务何时进行结束。

So if you want to force it use flush() after commit. 因此,如果要强制执行,则在提交后使用flush()。 If you can wait check after the session/transaction is being closed. 如果您可以等待,请在会话/事务关闭后再检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM