Issue
I am new to spring. I am creating Rest API using spring boot with JPA. I want to add multiple rows to database MYSQL.
I have created controller where i am using save() method from repository to insert data into database. I want to add multiple rows to database but when i run the code only last value is added in database. If i try to create Userskill object for method each time it works fine but it is not feasible to create new object each time. This is portion of code of controller. Here, Userskill is model and table into which i want to insert a data.
for(int i=0;i<listofskill.size();i++)
{
userskill.setUser_id(userid);
userskill.setSkill_id(skillRepo.findByName(listofskill.get(i)).getSkill_id());
userskillRepo.save(userskill);
}
this code only add 1 row with last value. I want to add each value to the database.
Solution
You can create list of Userskill then add all the elements at once, check below code:
List<UserSkillObject> userskillList = new ArrayList<>();
for(int i=0;i<listofskill.size();i++){
UserSkillObject userskill = new UserSkillObject();
userskill.setUser_id(userid);
userskill.setSkill_id(skillRepo.findByName(listofskill.get(i)).getSkill_id());
userskillList.add(userskill);
}
userskillRepo.saveAll(userskillList);
Answered By - user3153014
Answer Checked By - Willingham (JavaFixing Volunteer)