2017-08-31 46 views
0

我有一個包含'Job'實體的列表。所以我需要插入數據庫的列表作爲批處理,而無需迭代。什麼是最好的方式來做到這一點?如何插入列表<Object>數據庫使用休眠沒有迭代?

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

} 
+0

你想要一個迭代爲你解決?因爲在某些點上,該列表需要迭代.. – AxelH

+0

https://stackoverflow.com/questions/20458401/how-to-insert-multiple-rows-into-database-using-hibernate – Sarkhan

回答

1

如果使用的是春天,

  1. 使用地圖,而不是名單。 Map<String, Job> jobs = new HashMap<>();

  2. 將作業添加到地圖。

  3. 保存一氣呵成:jobRepository.save(jobs)