我有以下书籍和作者实体,作者与本书之间具有oneToMany关系

@Entity
@Table(name = "Author")
public class Author {

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

@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> bookList;

gettters/setters

}




@Entity
@Table(name = "Book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "authorId")
private Author author;

getters/setters
}


我的控制器

@PostMapping("/author")
public ResponseEntity<?> save(@RequestBody Author author) {
    long id = bookService.save(author);
    return ResponseEntity.ok().body("New Book has been saved with ID:" +id);
}


道课

@Override
public long save(Author author) {
    sessionFactory.getCurrentSession().save(author);
    return author.getId();
}


我正在使用以下输入来调用上述Web服务:

{
"name":"Herbert shilde",
"bookList":[{
    "title":"My Book"
}]
}


在我的数据库中,作者表正在插入正确的数据,但书表未插入相应记录的外键。如您在下图中所看到的,book表中的authorId为null。我正在使用休眠5。

作者表

java - 在Hibernate 5中,表的外键值不会自动更新-LMLPHP

书桌

java - 在Hibernate 5中,表的外键值不会自动更新-LMLPHP

任何帮助,将不胜感激

最佳答案

更改

@JoinColumn(name = "authorId")




@JoinColumn(name = "authorId", referencedColumnName = "id")

08-07 04:01