I need to load all files from the directory to the bytea field of PostgreSql database. File name contains the key value, i.e. "1.jpg". How can I achieve it with Spring Batch? I have some expirience with Spring Batch, but never worked with files and blob fields.
CodePudding user response:
You can design the type of your items as follows for example:
class FileItem {
String name;
byte[] content;
}
and use a ItemPreparedStatementSetter
that sets the image content with PreparedStatement#setBytes
. This custom prepared statement setter can be used with the JdbcBatchItemWriter
.
CodePudding user response:
I resolved this problem by myself.
ImageDto:
public class ImageDto {
private long id;
private byte[] image;
//getters and setters
}
ItemReader:
@Bean
public ItemReader<File> modelImageLargeReader() throws IOException {
List<File> files = Files.walk(Paths.get(appProperties.getSkiImagesLarge()))
.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
return new IteratorItemReader<>(files);
}
ItemProcessor:
@Bean
@StepScope
public ItemProcessor<File, ImageDto> modelImageProcessor() {
return item -> {
var imageDto = new ImageDto();
var fName = item.getName();
var index = fName.indexOf('.');
var strId = fName.substring(0, index);
imageDto.setId(Long.valueOf(strId));
imageDto.setImage(Files.readAllBytes(item.toPath()));
return imageDto;
};
}
ItemWriter:
@Bean
public ItemWriter<ImageDto> modelImageLargeWriter() {
return new JdbcBatchItemWriterBuilder<ImageDto>()
.dataSource(dataSource)
.sql("update model set image_large = :image where id_model = :id")
.beanMapped()
.build();
}