![](/img/trans.png)
[英]Spring Boot JPA One-to-One mapping generates StackOverflow Error
[英]One to One mapping get null value Spring boot JPA Hibernate
我已經實現了一對一的關系,當我嘗試插入值時,它給出了以下異常。
我已經嘗試了很多 stackoverflow 的答案,但還沒有運氣。 我無法弄清楚出了什么問題。
例外 :
org.springframework.dao.DataIntegrityViolationException:非空屬性引用空值或瞬態值
not-null 屬性引用空值或瞬態值
全包實體
@Entity(name = "FullPack")
@Table(name = "fullpack")
@TypeDefs({
@TypeDef(name = "json", typeClass = JsonStringType.class),
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class FullPack {
@Id
@Column(name = "fullpack_id")
int fullPackId;
@Type(type = "json")
@Column(columnDefinition = "json")
private String sequence;
@Type(type = "json")
@Column(columnDefinition = "json")
private String channelRestriction;
@Type(type = "json")
@Column(columnDefinition = "json")
private String actNotAllowed;
@Type(type = "json")
@Column(columnDefinition = "json")
private String packCompose;
}
包裝序列實體
@Entity
public class PackSequence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int packSequenceId;
int sequenceId;
int packId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fullpack_packsequence_id", referencedColumnName = "fullpack_id", nullable = false)
private FullPack fullPack;
}
向 FullPack 表插入記錄(有意為 JSON 字段插入空值)
{
"fullPackId": 1,
"sequence": null,
"channelRestriction": null,
"actNotAllowed": null,
"packCompose": null
}
將記錄插入到 PackSequence 表
從 Chun 的回答更新,但存在同樣的問題
{
"sequenceId":1,
"packId":2,
"fullpack" : {
"fullpack_id":1
}
}
Mysql 表結構
整包表
我相信這可能與從 Postman 到 PackSequence 的 Json 轉換有關,並且 FullPack 對象已發出
您將需要使用 JsonProperty 來幫助重新映射字段名稱。
我必須修改你的 PackSequence 和 FullPack 對象如下
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class PackSequence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int packSequenceId;
int sequenceId;
int packId;
@OneToOne()
@JoinColumn(name = "fullpack_packsequence_id", referencedColumnName = "fullpack_id", nullable = false)
@JsonProperty("fullpack")
private FullPack fullPack;
// omit getter and setter
}
@Entity(name = "FullPack")
@Table(name = "fullpack")
@JsonIgnoreProperties(ignoreUnknown = true)
public class FullPack
{
@Id
@Column(name = "fullpack_id")
@JsonProperty("fullpack_id")
int fullPackId;
private String sequence;
private String channelRestriction;
private String actNotAllowed;
private String packCompose;
// omit getter and setter
}
假設您通過 RestController 等從 JSON Payload 插入對象。
PackSequence json 對象應如下所示
{
"sequenceId":1,
"packId":2,
"fullpack" : {
"fullpack_id":1
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.