Movie class has a list of his sessions and I want to persist simultaneously the movie and his sessions stored in the list.
So here is my code
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;
}
test code
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 generated by 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.
so what's the problem? And when I only used @onetomany without @manytoone the same test works fine the foreign key is successfully added.