Hi I am developing some examples on how to use JPA and Hibernate and I have found one thing that I am not sure why it is happening.
I have a typical application with two POJOS related with a onetomany relationship:
Code:
@OneToMany(mappedBy="movie", cascade = CascadeType.ALL, orphanRemoval = true) //<1>
private List<Comment> comments = new ArrayList<Comment>();
And the counterpart:
Code:
@ManyToOne
private Movie movie;
Then I have one stateless bean that creates a new comment to a known movie.
Code:
public void createComment(Long movieId, Comment comment) {
Movie movie = entityManager.getReference(Movie.class, movieId);
comment.setMovie(movie);
entityManager.persist(comment);
}
And my Arquillian test looks like:
Code:
@Test
@ApplyScriptBefore("scripts/drop-referential-integrity.sql")
@UsingDataSet("datasets/movies-with-comments.yml")
@ShouldMatchDataSet("datasets/expected-movies-with-comments.yml")
public void shouldAddCommentPerformant() {
Comment comment = new Comment();
comment.setReview("must see");
moviesService.createComment(1L, comment);
}
No secrets here. But when I execute the test I see next queries that are executed by hibernate:
Code:
Hibernate: select movie0_.id as id1_1_1_, movie0_.releasedYear as released2_1_1_, movie0_.title as title3_1_1_, moviedetai1_.id as id1_2_0_, moviedetai1_.directedBy as directed2_2_0_, moviedetai1_.producedBy as produced3_2_0_ from Movie movie0_ left outer join MovieDetail moviedetai1_ on movie0_.id=moviedetai1_.id where movie0_.id=?
Hibernate: insert into Comment (id, movie_id, review) values (default, ?, ?)
Why this select is executed? I thought that using getReference was exactly to avoid this. You can see full code at https://github.com/Scytl/jpaguide/tree/master/sources/hibernate-performance-example
Thank you so much for your help.