我正在Spring数据Jpa中使用OneToMany关系,并使用postMan测试api。
@Entity
@Table(name = "book_category")
public class BookCategory {
ParentEntity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "bookCat_id")
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy="bookCategory")
private Set<Book> books;
public BookCategory(String name, Set<Book> books) {
this.name = name;
this.books = books;
}
// getter and setter
}
ChildEntity
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private Long bookId;
private String name;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "bookCat_id")
BookCategory bookCategory;
public Book() {
}
//getter and Setter
}
控制器类
@RestController
@RequestMapping(value = "/bookCategory")
public class BookController {
@Autowired
BookCategoryRepository bookCategoryRepository;
@Autowired
BookRepository bookRepository;
@PostMapping("/addBookCategory")
public BookCategory savePerson(@Valid @RequestBody BookCategory bookCategory){
return bookCategoryRepository.save(bookCategory);
}
}
从邮递员调用 Rest API 并将 json 作为
{
"name":"Category 1",
"books":[
{"name" : "Hello Koding 1"},
{"name":"Hello Koding 2"}
]
}
以下查询由Hibernate执行查询也是正确的,而我调用Rest点的东西 Hibernate:插入到book_category(名称)值 (?) 中Hibernate:插入到书籍中(book_cat_id,名称)值 (?, ?)
它没有插入book_cat_id,book_cat_id它传递空值,所以空正在存储
存储在数据库中的数据book_category数据库中的父表
书(子表) 书(子表) 我想得到子表 就像我想要这样的桌子一样
问题是您没有在子对象中设置父对象。在代码中的某个地方,您应该调用
public void setBookCategory(BookCategory bookCategory) { ... }
书籍实体的方法。
我建议通过在控制器中使用 DTO 并将它们映射到服务层中的实体来解决此问题,因为使用永久实体作为 http 请求的参数可能会导致严重的安全漏洞,如此处所述。
编辑:或者,即使认为我不鼓励这个解决方案是像这样修改savePerson方法
@PostMapping("/addBookCategory")
public BookCategory savePerson(@Valid @RequestBody BookCategory bookCategory){
bookCategory.getBooks().forEach(book -> book.setBookCategory(bookCategory));
return bookCategoryRepository.save(bookCategory);
}