【发布时间】:2019-03-25 14:46:52
【问题描述】:
我是 Springboot 的新手。我正在尝试使用以下方法实现一个简单的 REST api:
-Springboot,JPA & rest以及hibernate
我有一个 2 个表的数据库,包含 1 到多个笔记的笔记本
我已经设置了 2 个表和关系。我还创建了一个 NotebookRepository 和 NoteRepository 来通过 springboot rest 获取基本的 CRUD 操作。数据库连接和关系正在运行
但我不知道如何添加新笔记(它有一个 notebook_id 外键,不能为空),每次我尝试按照这些方式发布一些东西
{
"标题:"abc",
“文本”:“随便”,
“笔记本”:{
“身份证”: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>{
}
【问题讨论】:
标签: rest spring-boot spring-data-jpa