问题描述
我已经实现了一对一的关系,当我尝试插入值时,它给出了以下异常。
我尝试了很多stackoverflow答案,但是还没有运气。我不知道出了什么问题。
例外:
org.springframework.dao.DataIntegrityViolationException:不为空 属性引用了一个空值或瞬态值
非空属性引用空值或瞬态值
FullPack实体
@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表结构
FullPack表
解决方法
我相信这很可能与从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
}
}