Sobes.tech
Junior — Middle

What is the performance difference between using List and Set for @OneToMany annotation?

sobes.tech AI

Answer from AI

When using the @OneToMany annotation in JPA, the choice between List and Set affects performance and collection behavior.

  • List — an ordered collection that allows duplicates. When loading data, Hibernate creates a list that preserves the order of elements. This may require additional work to maintain indexes (for example, using @OrderColumn), which can impact performance during insertions and updates.

  • Set — an unordered collection without duplicates. Using Set is generally faster for checking the presence of an element and adding new elements, as it does not need to maintain order or indexes. However, the order of elements is not guaranteed.

Summary: If order is important and duplicates are allowed, it's better to use List, but this may reduce performance due to the need to maintain order. If order is not important and duplicates should be avoided, Set will be faster and more efficient.

Example:

@OneToMany(mappedBy = "parent")
private Set<Child> children = new HashSet<>();

// or
@OneToMany(mappedBy = "parent")
@OrderColumn(name = "order_index")
private List<Child> children = new ArrayList<>();