gpt4 book ai didi

java - 如何在 FlatFileItemReader 中使用 @JoinColumn 属性(实体)映射 CSV 字段 - Spring Batch

转载 作者:行者123 更新时间:2023-12-01 23:42:28 36 4
gpt4 key购买 nike

我正在使用 spring 批处理作业将数据从 CSV 文件插入到 MySql 表中。实体属性之一是使用 @ManyToOne 生成的 JoinColumn我的问题是 CSV 文件上的 ManyToOne 属性字段被视为实体 @ID 字段,并且未与生成错误的 JoinColumn 映射,

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String dept;
private Integer salary;
private Date endDate;
private Date time;
@ManyToOne
@JoinColumn(name = "carId", referencedColumnName = "id", foreignKey=@ForeignKey(name = "FK_Car_User"))
private Car car;
.....

Csv 文件:

car_id,name1,dept1,salary1,endDate
1,Peter,001,12000,1970-07-28
2,Sam,002,13000,1970-07-28
1,Ryan,003,10000,1970-07-28

线映射器

    lineTokenizer.setDelimiter(",");
lineTokenizer.setStrict(false);
lineTokenizer.setNames(new String[]{"carId", "name2", "dept2", "salary2","endDate"});

Map<Class<?>, PropertyEditor> editors = new HashMap<>();
CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
editors.put(Date.class, dateEditor);

BeanWrapperFieldSetMapper<User> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
fieldSetMapper.setTargetType(User.class);
fieldSetMapper.setCustomEditors(editors);

defaultLineMapper.setLineTokenizer(lineTokenizer);
defaultLineMapper.setFieldSetMapper(fieldSetMapper);

错误是:

Data Saved for Users: [User{id=1, name='Peter', dept='Technology', salary=12000}, User{id=2, 
name='Sam', dept='Operations', salary=13000}, User{id=1, name='Ryan', dept='Accounts',
salary=10000}]
2019-10-05 18:49:56.308 WARN 8984 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper :
SQL Error: 23502, SQLState: 23502
2019-10-05 18:49:56.308 ERROR 8984 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper :
NULL not allowed for column "CAR_ID"; SQL statement:
insert into user (id, car_id, dept, end_date, name, salary, time) values (null, ?, ?, ?, ?, ?, ?)
[23502-197]

感谢您的建议

最佳答案

该解决方案包括:1- 创建自定义 FieldSetMapper 类,而不是使用 BeanWrapperFieldSetMapper。2-在FieldSetMapper自定义类中 Autowiring 对象CarService(从存储库中获取汽车)3-在mapFieldSet(FieldSet fs)方法的实现中设置@ManyToOne属性如下user.setCar(carService.getCarById(fieldSet.readString("carId")));

关于java - 如何在 FlatFileItemReader 中使用 @JoinColumn 属性(实体)映射 CSV 字段 - Spring Batch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58253072/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com