I am trying to insert items in a list in a database as single values in rows with the name of the sender. I am able to send the payload and insert into a single row with the user detailst. How can I loop through the payload sent and insert all the items into individual rows? I have tried to look for examples no luck. So far I can only insert as a single row in the database
this is the payload
{"labsigned":["234568","234567","2345678","2344556","12335677","2345677","234556","234545"]}
My controller
@RequestMapping(path = "/labreport/createrordispatched", method = RequestMethod.POST) public ResponseEntity<?> createDispatched(@RequestBody Dispatched dispatched){ if(labDashboardService.createDispatched(dispatched)) { return ResponseEntity.status(HttpStatus.CREATED).body(true); } return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(false); }
My Service
public boolean createDispatched(Dispatched dispatched) { dispatched.setCreatedBy(getCurrentUserEmail()); dispatched.setDateCreated(System.currentTimeMillis()); Dispatched ticket = new Dispatched( dispatched.getCreatedBy(), dispatched.getDateCreated(), dispatched.getlabsigned() ); dispatchedRepository.save(ticket); return false; }
My Model
@Entity @Table(name = "DISPATCHED") public class Dispatched { private String id; private String labsigned; private Long dateCreated; private String createdBy; public Dispatched(){} public Dispatched(String createdBy, Long dateCreated, String labsigned){ this.labsigned = rorlabsigned; this.dateCreated = dateCreated; this.createdBy = createdBy; }
Advertisement
Answer
Assuming that you were able to insert all labsigned
in the payload into one single row with the code you mentioned in the question, You should iterate dispatched.labsigned
and insert one by one as rows to accomplish what you need. And returning false at the end of method createDispatched
will always return HttpStatus.BAD_REQUEST
even though the records are successfully saved in the DB, so you might need to change it to return true
.
public boolean createDispatched(Dispatched dispatched) { List<Dispatched> newTickets = new ArrayList<>(); dispatched.setCreatedBy(getCurrentUserEmail()); dispatched.setDateCreated(System.currentTimeMillis()); for(String labSigned:dispatched.getlabsigned()){ Dispatched ticket = new Dispatched( dispatched.getCreatedBy(), dispatched.getDateCreated(), labSigned ); newTickets.add(ticket); } dispatchedRepository.saveAll(newTickets); return true; }