在for循环中保存操作

时间:2015-03-31 13:16:14

标签: java spring hibernate for-loop

我在春天工作mvc + hibernate .....

我在for循环中进行创建操作,但它只执行一次。这是我的示例代码。

        String[] loanIds = request.getParameterValues("loanId");

loanIds值为5

        for (String string : loanIds) {                 
            loanFinance.setFundingBankId(bankId);
            loanFinance.setIdFundsProductPurpose(Long.valueOf(68449));
            loanFinance.setLoanId(Long.parseLong(string));
            loanFinance.setLastModifiedBy(user.getId());
            loanFinance.setIdEntityloan(Long.parseLong(string));
            loanFinance.setAmount(10000.00);
            loanFinance.setStatus("A"); 

            commonRepository.save(loanFinance);     
            System.out.println("Saved Datas");
        }

我catalina.out我可以看到" Saved Datas"打印5次....但表只插入一次。

任何人都可以给我这方面的建议,我在这里做错了什么..

3 个答案:

答案 0 :(得分:3)

我相信你必须为你迭代的每个字符串创建一个新的LoanFinance对象。

答案 1 :(得分:2)

您一遍又一遍地保存同一个对象。如果要插入5个不同的元素,则需要在每次迭代时创建一个新元素。

 for (String string : loanIds) {  
        loanFinance = new LoanFinance();               
        loanFinance.setFundingBankId(bankId);
        loanFinance.setIdFundsProductPurpose(Long.valueOf(68449));
        loanFinance.setLoanId(Long.parseLong(string));
        loanFinance.setLastModifiedBy(user.getId());
        loanFinance.setIdEntityloan(Long.parseLong(string));
        loanFinance.setAmount(10000.00);
        loanFinance.setStatus("A"); 

        commonRepository.save(loanFinance);     
        System.out.println("Saved Datas");
    }

答案 2 :(得分:-1)

GIOVANNI的扩展答案

@PostMapping(" multiplevents&#34)     public void createStgSlobMultiEvents(@RequestBody EcStgSlobEvents createEcStgSlobEvents             ){

    logger.info(" createEcStgSlobEvents --->   " + createEcStgSlobEvents);

    logger.info(" EcStgSlobEventController::: createStgSlobMultiEvents ()  ");

    List<Integer> eventids = createEcStgSlobEvents.getEvenIds();
    EcStgSlobEvents ecStgSlobEvents =null;
    for (Integer eventId : eventids) {
         ecStgSlobEvents = new EcStgSlobEvents();

        ecStgSlobEvents.setCliCode(createEcStgSlobEvents.getCliCode());
        ecStgSlobEvents.setEventId(eventId);
        ecStgSlobEvents.setLineOfBusiness(createEcStgSlobEvents.getLineOfBusiness());
        ecStgSlobEvents.setSlobEventId(createEcStgSlobEvents.getSlobEventId());
        ecStgSlobEvents.setSublineOfBusiness(createEcStgSlobEvents.getSublineOfBusiness());

        createEcStgSlobEvents.setEventId(eventId);
        logger.info(" EcStgSlobEventController::: EventId  " + eventId);
        eventConfigurerepo.save(ecStgSlobEvents);
    }
    logger.info(" EcStgSlobEventController::: createStgSlobEvents - multiplevents()  ");

}