[英]Jpa @onetomany can't generate foreign key for the inverse side
電影 class 有他的會話列表,我想同時保留存儲在列表中的電影和他的會話。
所以這是我的代碼
public class Movie {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "movie_id")
private int movieId;
...
@OneToMany(mappedBy = "movie",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Session> sessionList = new ArrayList<>();
}
public class Session {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "session_id")
private int sessionId;
...
@ManyToOne
@JoinColumn(name = "movie_id")
private Movie movie;
}
測試代碼
public void testAddMovie(){
Session session1 = new Session();
session1.setDay("Monday");
Movie movie = new Movie();
movie.setTitle("hello");
movie.getSessionList().add(session1);
movieDao.addMovie(movie);
}
sql 由 hibernate 生成
insert
into
movies
(actors, .... ,title)
values
(?, ?, ?, ?, ..., ?, ?, ?, ?)
insert
into
sessions
(day, movie_id, time)
values
(?, ?, ?)
Hibernate throws no exception, and both movie and session are successfully persisted but the foreign key 'movie_id' in the table session show always null.
所以有什么問題? 當我只使用沒有@manytoone 的@onetomany 時,同樣的測試工作正常,外鍵被成功添加。
在 Session 實體中,將電影屬性更改為:
@ManyToOne
@JoinColumn(name = "movie_id", foreignKey = @ForeignKey(name = "fk_session_movie."))
private Movie movie;
事實證明,我錯過了部分代碼。 這是解釋原因的鏈接。 JPA @OneToMany:外鍵是 null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.