我需要将一个大的.csv加载到我的数据库中,我有一个Price实体,该实体引用了一个Distributor:
public class Price {
@Id
private String id;
private Date dtComu;
private Double price;
@ManyToOne
@JoinColumn(name = "idDistributor")
private Distributor distributor;
//constrcutor, getters&setters
我尝试上传的带有价格数据的csv对每个价格都有对分销商ID的引用。在ItemReader上,我有:
public FlatFileItemReader<Price> priceReader() {
FlatFileItemReader<Price> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("file.csv"));
reader.setLinesToSkip(2);
reader.setRecordSeparatorPolicy(recordSeparatorPolicy);
reader.setLineMapper(new DefaultLineMapper<Price>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setStrict(false);
setDelimiter(";");
setNames(new String[] { "idDistributor", "price", "dtComu" });
}
});
setFieldSetMapper(customMapper());
}
});
return reader;
}
我的customMapper是:
public class CustomMapper implements FieldSetMapper<Price> {
@Autowired
DistributorRepository repository;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
@Override
public Price mapFieldSet(FieldSet fieldSet) throws BindException {
Distributor distributor = repository.findById(fieldSet.readInt("idDistributor")).orElse(null);
if (distributore == null) {
return null;
}
Price p = new Price();
p.setDistributor(distributor);
p.setPrice(fieldSet.readDouble("price"));
try {
p.setDtComu(formatter.parse(fieldSet.readString("dtComu")));
} catch (ParseException e) {
// TODO Auto-generated catch block
p.setDtComu(new Date());
}
//here i will crate an ID for the Price that i need to always be unique
p.setId(distributor.getIdImpianto()+ fieldSet.readString("dtComu"));
return p; }}
我的作家如下:
public JdbcBatchItemWriter<Price> prezzoWriter() {
JdbcBatchItemWriter<price> writer = new JdbcBatchItemWriter<Price>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Prezzo>());
;
writer.setSql("INSERT INTO price (id_distributor, price, dt_comu) "
+ "VALUES (:idDistributor, :price, :dtComu");
writer.setDataSource(dataSource);
return writer;
}
我运行该程序,它没有任何保存就完成了。我会做错什么吗?我只是从Sring Batch开始的,所以必须详细说明一下。
在JdbcBatchItemWriter
一无所知的情况下JPA。您需要使用a DataSourceTransactionManager
才能正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句