Batching Parent/Child Entities for Inserts

I’m trying to figure out how to batch inserts for a table that has a Parent/Child relationship with itself. Here’s an example of the class.

@Entity
@Table(name = "foo")
public class Foo {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "foo_foo_id_seq")
  @SequenceGenerator(name = "foo_foo_id_seq", sequenceName = "foo_foo_id_seq")
  @Column(name = "foo_id", nullable = false)
  private Integer id;

  @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @OnDelete(action = OnDeleteAction.CASCADE)
  @JoinColumn(name = "parent_foo_id")
  private Foo parentFoo;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentFoo", cascade = CascadeType.ALL)
  private Set<Foo> children;

Then when I try to insert two entities using the following code:

List<Foo> savedFoos = new ArrayList<>();
...
fooRepository.saveAll(savedFoos);

The list contains one entry. The parent entity has the child entity in the children set, and the child had the parentFoo set to the parent entity.

I get the following message.

The batch containing 2 statements could not be sorted. This might indicate a circular entity relationship.

I do have the order_inserts and batch_size properties set.

spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.jdbc.batch_size=50

The log message says it all. The statement ordering logic is not able to sort statements in this kind of scenario, because you have a cycle in your model. If only Foo entities are persisted though, this wouldn’t matter much since statements would naturally be ordered already, hence you can leverage batching.