我面临着一对多双向关系的问题。我遇到了将元素B(很多)添加到A(一个)的问题。我想在实体中添加新元素。 有我的数据库架构: DB Schema
有我的A实体:
public class Application {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int Id;
@Column(name = "has_paid")
private boolean paid;
@Column(name = "is_accepted")
private boolean accepted;
@OneToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
private List<Player> players;
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
public void addPlayers(Player player){
System.out.println("---------------1");
player.setApplication(this);
System.out.println("---------------2");
this.players.add(player);
System.out.println("---------------3");
}
}
这是我的B实体:
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int Id;
private String name;
private String role;
private String size;
@ManyToOne
@JoinColumn(name = "application_id")
private Application application;
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}}
所有课程都有适当的getter和setter
我的服务类:
@ResponseStatus(HttpStatus.CREATED)
@Transactional(rollbackFor = Exception.class)
@Override
public Object create(ApplicationsPostDTO applicationsRequest){
if(Optional.ofNullable(applicationsRequest).isPresent()){
System.out.println(applicationsRequest.toString());
Application application = new Application();
application.setTeam(teamsRepositories.findById(applicationsRequest.getTeam_id()).orElseThrow(BadRequestException::new));
application.setAccepted(applicationsRequest.isAccepted());
application.setPaid(applicationsRequest.isPaid());
System.out.println(application.toString());
applicationsRequest.getPlayers().forEach(it -> {
System.out.println(it.toString());
application.addPlayers(it);
});
System.out.println(application.toString());
return applicationsRepositories.save(application);
}else{
throw new BadRequestException();
}
}
错误跟踪: Screen number 1
答案 0 :(得分:0)
这是一个简单的问题,您在添加之前忘记检查List
是否为null。
您要么检查null并实例化List
,要么直接在该字段上添加实例。
@OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
private List<Player> players = new ArrayList<>();