0

I have a List which are include 'Job' Entities. So I need to insert to database that List as a batch without iterating. what is the best way to do that?

@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public JobResult save(JobDTO dto) throws Exception {

    JobResult result = new JobResult(new Job(), dto);
    try {
        JobMapper.getInstance().dtoToDomain(result.getDtoEntity(), result.getDomainEntity());
        setBatchJobData(result);
        result.addToMessageList("Jobs Added Successfully.");
        result.updateDtoIdAndVersion();
    } catch (Exception ex) {
        ex.printStackTrace();
        result.setResultStatusError();
        result.addToErrorList(ex.getMessage());
    }
    return result;

}

private void setBatchJobData(JobResult result) throws Exception{
    List<Job> jobs = new ArrayList<>();
    for (Integer scheduleTaskId : result.getDtoEntity().getScheduleTaskIds()) {
        Job job = new Job();
        AgreementScheduleTask agreementScheduleTask = agreementScheduleTaskDao.findOne(scheduleTaskId);
        setJobData(job, agreementScheduleTask);
        setAssets(job, agreementScheduleTask);
        jobs.add(job);
    }   

}
tharanga-dinesh
  • 537
  • 6
  • 26
  • You want a solution that iterate for you ? Because at some point that list need to be iterated.. – AxelH Aug 31 '17 at 09:37
  • https://stackoverflow.com/questions/20458401/how-to-insert-multiple-rows-into-database-using-hibernate – Sarkhan Aug 31 '17 at 09:40

1 Answers1

2

If you are using spring,

  1. use map instead of List. Map<String, Job> jobs = new HashMap<>();

  2. Add the Jobs to the Map.

  3. save at one go : jobRepository.save(jobs)

maya16
  • 593
  • 1
  • 6
  • 19