Bhoomi Vaghasiya
Bhoomi Vaghasiya

Reputation: 381

Insert multiple rows in database using spring boot JPA

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.

Upvotes: 1

Views: 14839

Answers (2)

user3153014
user3153014

Reputation: 318

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);

Upvotes: 2

Fajar AM
Fajar AM

Reputation: 116

try this

for(int i=0;i<listofskill.size();i++)
     {     
         UserSkillObject userskill  = new UserSkillObject ();
         userskill.setUserSkillId(newId);           
         userskill.setUser_id(userid);           
         userskill.setSkill_id(skillRepo.findByName(listofskill.get(i)).getSkill_id());
         userskillRepo.save(userskill);          
     }

Upvotes: 1

Related Questions