简体   繁体   English

如何在发生异常时继续批量插入

[英]How to Continue bulk inserts when exception occurs

I am using jpa with hibernate I want to insert 100 record in Database, suppose I get exception JDBC batch update in 50th record insertion i need to handling the Exception and I need to persist remaining record to DB. 我正在使用jpa与hibernate我想在数据库中插入100条记录,假设我在第50条记录插入时得到异常JDBC批量更新我需要处理异常并且我需要将剩余记录保存到DB。

Code: 码:

 private List<TempCustomers> tempCustomer =new ArrayList<TempCustomers>();

    public String migrateCustomers() {

      TempCustomers temp = null;
        for(DoTempCustomers tempCustomers:doTempCustomers){

              try {
                temp=new TempCustomers();
                BeanUtils.copyProperties(temp, tempCustomers);
                        tempCustomer.add(temp);
                    entityManager.persist(temp);


              }catch (Exception e) {
                  tempCustomer.add(temp);
                  entityManager.persist(temp);
                  log.info("Exception ..."+e);
                  return "null";
              }
        }


        return "null";
    }

Nagendra. Nagendra。

What Mr. RAS is telling is correct. RAS先生所说的是正确的。

For example you are persisting 100 entities and exception happened in the 50th Entity persist. 例如,您持有100个实体,并且在第50个实体持久性中发生了异常。 You have exception handler it will work for you to handle the situation. 你有异常处理程序,它可以帮助你处理这种情况。 It ll skip the current one and process the next one. 它将跳过当前的一个并处理下一个。

Things to take care as follows: 需要注意的事项如下:

1- Your exception handling should be within the loop, hope you already have it. 1-你的异常处理应该在循环内,希望你已经拥有它。

2- For exception you can save the entity in different list for further analysis for error details. 2-对于例外,您可以将实体保存在不同的列表中,以便进一步分析错误详细信息。 do it in the exception catch block. 在异常catch块中执行此操作。

3- I am not sure whether you are using the transaction manager or not, transaction need to take care. 3-我不确定您是否使用交易管理器,交易需要注意。

-- -

In the 2nd case please remove the line... 在第二种情况下,请删除该行...

entityManager.persist(temp); entityManager.persist(温度);

as you already know this throws exception. 因为你已经知道这会抛出异常。 keep it in the list for your further analysis. 将其保留在列表中以供进一步分析。 better put into any queue(ActiveMQ) upto you. 最好放入任何队列(ActiveMQ)。

Best solution for this is again: 最佳解决方案是:

Validate all your data before persist...to minimize the exception. 在持久化之前验证所有数据...以最小化异常。 runtime things need your re-processing again and that should be manual. 运行时事情需要再次重新处理,这应该是手动的。

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

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