微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

一对一映射获取空值Spring Boot JPA Hibernate

如何解决一对一映射获取空值Spring Boot JPA Hibernate

我已经实现了一对一的关系,当我尝试插入值时,它给出了以下异常。

我尝试了很多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表

enter image description here

PackSequence表

enter image description here

解决方法

我相信这很可能与从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
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。