I seem to get mixed answers with this, so I just wanted to clarify the behavior of JpaRepository. Given a JPA entity such as:
public class ItemEntity {
@Id
@SequenceGenerator(name = "i_seq", sequenceName = "i_seq, allocationSize = 1)
@@GeneratedValue(stragegy = GenerationType.SEQUENCE, generator = "i_seq")
@Column(name = "id", columnDefinition = "bigint")
private Long id;
...
}
The id is generated by a sequence on the database side. My goal is to insert the items in the order of the List.
public void saveAll(List<ItemEntity> items) {
...
}
The problem is, I don't believe that JpaRepository.saveAll actually enforces the insertion order. My question is, can I "force" JPA to insert the items in the order of the List by flushing every ItemEntity after the call to save?
public void saveAll(List<ItemEntity> items) {
for (ItemEntity item : items) {
jpaRepository.save(item);
jpaRepository.flush();
}
}
Or is the flush not required?
Short answer: No, flushing after each save is not required for insertion order — JpaRepository.saveAll
already processes entities in the same order as your input List
.
Explanation:
Spring Data JPA’s default saveAll
implementation (in SimpleJpaRepository
) iterates over the provided collection and calls save
for each element in sequence:
JPA itself doesn’t reorder these inserts — the SQL insert statements will be generated in the same sequence unless batching, flush modes, or database-level optimizations alter execution timing.
If you specifically need to persist and commit immediately, you can use:
repository.saveAllAndFlush(entities);