【问题标题】:Hibernate Transaction AnnotationHibernate 事务注解
【发布时间】:2020-12-14 06:53:44
【问题描述】:

我有一个关于注释的问题 我的班级:

@Override
@Transactional
public void process() {
  . . .
   send(persons);
}

public void send(List<person> persons) {
  . . .
   // person list size 1.000.0000
  for(...){
   update(persons); --> 1000, 1000 sending for loop
  }
}

public void update(List<person> persons){
   ...
   List<person> errorPersons;
   ...
   persons.forEach(person-> {
     person.setName("Google - " + person.getName());         
   });

   persons.removeAll(errorPersons);

   getSession().getTransaction().commit(); //--|
   getSession().beginTransaction();        //--| > is works!
   getSession().clear();                   //--|

   send(persons); //recursive

} 

它的工作原理如下。如何使用注释做到这一点?

   getSession().getTransaction().commit(); //--|
   getSession().beginTransaction();        //--| > is works!
   getSession().clear();  

我尝试了一些方法,但都不起作用,您能帮忙解决这个问题吗?

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void update(List<person> persons){
   getSession().getTransaction().commit(); //--> Not Working
}

@Transactional(propagation = Propagation.REQUIRES)
public void update(List<person> persons){
   getSession().getTransaction().commit(); //--> Not Working
}

我只是想做,怎么做这个更优化?

【问题讨论】:

    标签: java hibernate transactions annotations


    【解决方案1】:

    对此进行优化的一种方法是使用 ScrollableResult 来获取人员列表并使用类似的方法遍历 ScrollableResult

       ScrollableResults persons = query.scroll(ScrollMode.FORWARD_ONLY);
    
       while (persons.next()) {
           Person person = (Person) persons.get(0);
    
           // do the stuff you want to do with a person
    
           ++numberOfFormsHandled;
           if (numberOfPersonsHandled % 20 == 0) {
              flushAndClearSession();
           }
       }
    
       if (persons != null) {
           persons.close();
       }
    

    如果有用请告诉我。

    -Kaj :)

    【讨论】:

      【解决方案2】:

      你在用 Spring 吗?

      @Transactional 注释会围绕您的类/方法生成一个代理来处理事务。此代理只能在使用您的类的注入代理的客户端调用该方法时拦截。当您在同一个类中调用方法 update 时,您不会通过代理,因此您没有事务管理。

      @Transactional(propagation = Propagation.REQUIRES_NEW) 暂停当前事务(如果有),创建一个新事务,方法中的所有代码都由该事务管理。一旦方法以正常方式结束(无例外),事务就被提交并终止。调用后,外部事务再次受到控制。

      Spring @Transaction method call by the method within the same class, does not work?

      通常在使用@Transactional 注释时,您不会调用getSession().getTransaction().commit() 它已经为您完成了。

      【讨论】:

        猜你喜欢
        • 2015-11-18
        • 2023-04-08
        • 2015-08-20
        • 2011-02-24
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        • 2015-03-26
        • 1970-01-01
        相关资源
        最近更新 更多