Reputation: 567
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
Reputation: 633
If you are using spring,
use map instead of List. Map<String, Job> jobs = new HashMap<>();
Add the Jobs to the Map.
save at one go : jobRepository.save(jobs)
Upvotes: 2