gpt4 book ai didi

java - Hibernate @OneToMany 关联尝试设置 null FK 值

转载 作者:行者123 更新时间:2023-11-30 08:09:26 24 4
gpt4 key购买 nike

我有以下简单的例子。当它运行时,我看到使用自动生成的 id 生成了 QuoteRequest 对象。接下来,我看到正在生成 Accidents 对象,但插入的 quote_request_id 为 null,因此出现错误:

“quote_request_id”列不能为空

@Entity
@Table(name = "Quotes")
public class QuoteRequest
{
public QuoteRequest(){}

@Id
@Column(name = "quote_request_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long QuoteRequestId;


@OneToMany(mappedBy = "quoteRequest", cascade = CascadeType.ALL)
@OrderColumn(name = "accidents_id")
private Accidents[] accidents;

// Getters and setters
}

@Entity
@Table(name = "Accidents")
public class Accidents
{
public Accidents()
{
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "accidents_id")
private long AccidentId;


@Column(name = "amount", nullable = false)
private Float amount;

@ManyToOne(optional = false, cascade = CascadeType.ALL)
@JoinColumn(name = "quote_request_id", nullable = false)
private QuoteRequest quoteRequest;

// Getters and setters
}

为什么不将新生成的 ID 插入事故列中?

最佳答案

首先,将 @OneToMany 从使用数组更改为使用 List:

@OneToMany(mappedBy = "quoteRequest", cascade = CascadeType.ALL)
@OrderColumn(name = "accidents_id")
private List<Accidents> accidents = new ArrayList()<>;

确保您设置了关联的双方:

QuoteRequest quoteRequest = ...
Accidents accidents = ...

quoteRequest.getAccidents().add(accident);
accident.setQuoteRequest(quoteRequest);

关于java - Hibernate @OneToMany 关联尝试设置 null FK 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30611623/

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