【问题标题】:Hibernate bidirection one to many relation, adding elementHibernate双向一对多关系,添加元素
【发布时间】:2018-10-28 23:22:18
【问题描述】:

我面临一对多双向关系的问题。我在将元素 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

Screen number 2

【问题讨论】:

    标签: hibernate spring-data spring-data-jpa


    【解决方案1】:

    这是一个简单的 npe 问题,您忘记在添加之前检查您的 List 是否为空。

    您可以检查 null 并实例化 List 或直接在字段上添加实例化。

    @OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
    private List<Player> players = new ArrayList<>();
    

    【讨论】:

    • 现在,我得到了 stackoverflow。我试图只添加一名球员。似乎有什么东西在循环这个,并一遍又一遍地添加同一个玩家Error stack
    猜你喜欢
    • 2014-03-17
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多