当前位置:网站首页>JPA failed to save multiple entities circularly

JPA failed to save multiple entities circularly

2022-06-11 17:05:00 wozaizhe. fifty-five

  use JPA Cycle through multiple entities , The code is as follows :

for(A a : list){
    Test test = new Test();
    test.setId(a.getId());
    test.setName(a.getName());
    for(int i = 0; i < a.getTopics().size(); i ++){
        test.setTopic(a.getTopics().get(i));
        ITestDAO.save(test);
    }
}

Ideally ,  The outer loop is executed once , The inner layer circulates a.getTopic().size() Entity .  But that's not the case ,  Look at the database and you will find , just a.getTopics() The last element in the array (topic) The corresponding entity is saved ,  Are other elements (topic) Have the corresponding entities not been saved ? 

in fact ,  No, it isn't ,  in front topic The corresponding entity is also saved , Just by the back topic The corresponding entity is overwritten . Why is this so ?  because test Is instantiated in an outer loop ,  For the inner loop , test Objects are the same ,  So execute save() In operation , JPA Think back topic It's right up front topic Update .  So the outer loop executes once ,  Eventually at most one entity is saved .

If you want everyone to topic  The corresponding entities can be saved ,  Should be test The instantiation of is placed in the inner loop , as follows :

for(A a : list){
    for(int i = 0; i < a.getTopics().size(); i ++){
        Test test = new Test();
        test.setId(a.getId());
        test.setName(a.getName());
        test.setTopic(a.getTopics().get(i));
        ITestDAO.save(test);
    }
}

This is done every time save() In operation ,test Objects are different , Thus, it is possible to topic The preservation of the .

原网站

版权声明
本文为[wozaizhe. fifty-five]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111658245837.html