如何将json数据放到表的外键中?

时间:2018-01-26 20:36:51

标签: java hibernate jpa post

我有两个实体。

任务

public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "title")
    private String tilte;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name="project_id")
    private Project project;

    @ManyToOne
    @JoinColumn(name="task_status_id")
    private TaskStatus taskStatus;

}

项目

public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "project", fetch = FetchType.EAGER)
    private List<Task> tasks;

    @JsonIgnore
    @ManyToMany(mappedBy = "projects")
    private List<User> users;
}

当我创建新任务时,我发送帖子请求但是project_id有问题。我认为我的映射存在一些问题,因为请求写得正确。

错误: [WARN] 2018-01-27 00:08:41.103 engine.jdbc.spi.SqlExceptionHelper logExceptions(129)                      - SQL错误:1048,SQLState:23000 [错误] 2018-01-27 00:08:41.104 engine.jdbc.spi.SqlExceptionHelper logExceptions(131)                      - 专栏&#39; project_id&#39;不能为空

这是我的JSON帖子的例子:

{&#34;名称&#34;:newTask,&#34;标题&#34;:&#34; newTaskTitle&#34;&#34;项目&#34;:[{&#34; ID&# 34;:1,&#34; name&#34;:&#34; projectName&#34;}],&#34; taskStatus&#34;: [{&#34; id&#34;:1,&#34; name&#34;:&#34; taskStatusName&#34;}]}

1 个答案:

答案 0 :(得分:0)

我之所以这样说是因为你的DB的project_id FK设置为​​不可为空,你的Project属性有@JsonIgnore注释;您确实在JSON请求中发送项目,但它只是被Hibernate / JPA忽略,因此它保持为null并且违反了您的不可空DB限制。此外,如果DB字段不可为空,我建议你添加&#34; nullable = false&#34;为了防止Hibernate / JPA尝试做一些有趣的事情,请加入你的JoinColumn。

如果你删除注释,你很可能会进入某种类型的DetachedEntityException。双向是概念上的好,但在JSON和Hibernate中都很难处理;你可以查看my answer to a very similar question/problem