tharanga-dinesh
tharanga-dinesh

Reputation: 567

How to insert List<Object> to database using hibernate without Iterate?

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

}

Upvotes: 0

Views: 2282

Answers (1)

maya16
maya16

Reputation: 633

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)

Upvotes: 2

Related Questions