包含外键OnToMany映射的POST REST请求

时间:2019-03-25 14:46:53

标签: rest spring-boot spring-data-jpa

我是Springboot的新手。我正在尝试使用实现一个简单的REST api: -Springboot,JPA和休眠以及休眠

我有一个2表数据库,Notebook包含1到许多笔记 我已经设置了2个表和关系。我还创建了一个NotebookRepository和NoteRepository以通过springboot rest获得基本的CRUD操作。数据库连接和关系正在运行 但是我不知道如何添加新的笔记(它有一个notebook_id外键,不能为空),每次我尝试沿着这些行发布内容时
{  “标题:” abc”, “ text”:“任何”, “笔记本”:{ “ id”:2     } }
我收到此错误: 原因:java.sql.SQLIntegrityConstraintViolationException:列'notebook_id'不能为空

@Entity
@Table(name="notebook")
public class NoteBook {

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

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

    @OneToMany(mappedBy="notebook", cascade=CascadeType.ALL)
    List<Note> notes;

    public NoteBook() {

    }

    public NoteBook(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Note> getNotes() {
        return notes;
    }

    public void setNotes(List<Note> notes) {
        this.notes = notes;
    }

    public void addNote(Note note) {
        if(notes == null) {
            notes = new ArrayList<>();
        }
        note.setNotebook(this);
        notes.add(note);
    }

@Entity
@Table(name="note")
public class Note {

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

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

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

    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="notebook_id")
    private NoteBook notebook;

    public Note() {

    }

    public Note(String title, String text) {
        this.title = title;
        this.text = text;
    }

@RepositoryRestResource(collectionResourceRel = "note", path = "notes")
public interface NoteRepository extends JpaRepository<Note, Integer>{
    //No code...
}

@RepositoryRestResource(collectionResourceRel = "notebook", path = "notebooks")
public interface NotebookRepository extends JpaRepository<NoteBook, Integer>{

}

2 个答案:

答案 0 :(得分:0)

我认为您需要为Note类中笔记本字段的JoinColumn注释添加referencedColumnName =“ id”。

也许您对IDENTITY生成类型有疑问。参见this problem with null pointer

答案 1 :(得分:0)

问题在于类Note没有带有NoteBook参数的构造函数来将创建的NoteBook对象传递给它,因此解决方案是添加以下构造函数:

public Note(String title, String text, NoteBook noteBook) {
    this.title = title;
    this.text = text;
    this.noteBook = noteBook;
}

和发送JSON对象一样,就足够了,但是要注意区分大小写:

{ "title:"abc", "text":"whatever", "noteBook":{ "id":2 } }