I have a unidirectional, one-to-many, parent/child relation. In my test case, I have 1 parent with 2 children which are inserted via cascading insert.
Looking at the queries that are ran, I have 1 insert for the parent, 1 insert and two update queries for each of the children. The updates for the foreign key - they are setting the parent_id column in the child table, but I can see that the parent_id has already been set correctly by the insert.
Here is an example
@Entity
@Table(name = "PARENT")
public class Parent
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long parentId;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", nullable=false)
private List<Child> children;
}
@Entity
@Table(name = "CHILD")
public class Child
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "PARENT_ID")
private Long parentId;
//some other field
}
//The test looks like this
Parent parent = new Parent();
Child child1 = new Child();
Child child2 = new Child();
//set all fields
parent.addChild(child1);
parent.addChild(child2);
em.merge(parent);
Is it possible to not have the update queries? Is it possible to insert all children in a single query?