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

时间:2018-09-19 09:49:20

标签: java spring hibernate

我有以下书籍和作者实体,作者与书之间具有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"   
}]
}

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

作者表

enter image description here

书桌

enter image description here

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:-1)

更改

@JoinColumn(name = "authorId")

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