I have a bidirectional one to many relationship as follows. And in my test, I insert one parent and 3 children entities. Then I count the number of prepared statements. Hibernate tells me it's 6 but in the log I see only 4 insert statements logged. Why is this happening?
public class Order {
@Id
private Long id;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Line> lines = new ArrayList<>();
public void addLine(Line line) {
lines.add(line);
line.setOrder(this);
}
}
public class Line {
@Id
private Long id;
@ManyToOne
private Order order;
}
Test
@Test
public void test() {
Statistics stat = entityManager.unwrap(Session.class).getSessionFactory().getStatistics();
Line line1 = Line.builder().lineNbr("1").build();
Line line2 = Line.builder().lineNbr("2").build();
Line line3 = Line.builder().lineNbr("3").build();
Order order = Order.builder().orderNbr("1").lines(new ArrayList<>()).build();
order.addLine(line1);
order.addLine(line2);
order.addLine(line3);
repo.saveAndFlush(order);
assertEquals(4, stat.getEntityInsertCount());
assertEquals(4, stat.getPrepareStatementCount()); // this fails. Hibernate says it's 6
}
This is what I see in the log:
Hibernate: insert into orders (order_nbr, id) values (?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)
Hibernate: insert into line (line_nbr, order_id, id) values (?, ?, ?)
927500 nanoseconds spent preparing 6 JDBC statements;
2732200 nanoseconds spent executing 4 JDBC statements;
2118000 nanoseconds spent executing 2 JDBC batches; -------- what is this?