My goal is that while I am processing my files, to also add them in a persistent H2 instance with their current status: “NEW” during reading, “PROCESSING” in the ItemProcessor, and “COMPLETED” in the ItemWriter. When I initialize the rows inside the ItemReader, I can query and verify their addition using a print statement in Java, by finding them inside the repository using their names. However, in the ItemProcessor step, when I attempt to do the same, I get an error indicating that there is no such object in the database. I understand this issue is related to the way transactions are handled in Spring Batch. Shouldn’t it flush the session after the write step, rather than between steps?
@Override
public synchronized FileEntry read() throws IOException {
if (fileIterator.hasNext()) {
FileEntry fileEntry = fileIterator.next();
fileEntry.setBatchName(currentBatchName);
fileEntry.setContent(fileSystemService.readFile(inboundDirectory + "/" + currentBatchName + "/" + fileEntry.getName()));
String metaDataFile = fileEntry.getName().replace(".pdf", ".xml");
fileEntry.setMetaData(fileSystemService.readFile(inboundDirectory + "/" + currentBatchName + "/" + metaDataFile));
batchFileService.save(new BatchFile(fileEntry.getName(), currentBatchName));
System.out.println(batchFileService.findByName(fileEntry.getName())); //here it does not return null
return fileEntry;
}
return null;
}
Here in the processor, I get that BatchFile is null
BatchFile batchFile = batchFileService.findByName(fileEntry.getName());
batchFile.setStatus("PROCESSING");
batchFileService.save(batchFile);
My BatchFile entry
package com.pgi.efsa.batch.sign.model;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@NoArgsConstructor
@Table(name="BATCH_FILES")
public class BatchFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String status;
private String batchName;
public BatchFile(String name, String batchName) {
this.name = name;
this.batchName = batchName;
this.status = "NEW";
}
}
The service
package com.pgi.efsa.batch.sign.service;
import com.pgi.efsa.batch.sign.model.BatchFile;
import com.pgi.efsa.batch.sign.repository.BatchFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Component
public class BatchFileService {
@Autowired
private BatchFileRepository batchFileRepository;
@Transactional
public BatchFile findByName(String name) {
return batchFileRepository.findByName(name);
}
@Transactional
public long save(BatchFile batchFile) {
return batchFileRepository.save(batchFile).getId();
}
}