A set is a collection of distinct elements: adding the same element again does not create a duplicate. In reactive persistence, a Taco uses a set of ingredient IDs to guarantee that each ingredient appears only once. section 13.1.1
A set is useful when:
- Uniqueness matters, such as preventing the same ingredient from being added twice. section 13.1.1
- The collection represents references rather than complete related entities; Taco stores Set<Long> ingredient IDs. section 13.1.1
Adding taco ingredients
A Taco initializes ingredientIds with HashSet<>. Its addIngredient method adds an ingredient's ID, so repeated additions of the same ID remain a single entry.
Listing 13.2 The Taco entity class for R2DBC persistence
package tacos;
import java.util.HashSet;
import java.util.Set;
import org.springframework.data.annotation.Id;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class Taco {
@Id
private Long id;
private @NonNull String name;
private Set<Long> ingredientIds = new HashSet<>();
public void addIngredient(Ingredient ingredient) {
ingredientIds.add(ingredient.getId());
}
}
Inspect the complete Taco entity, including its Set<Long> collection and addIngredient method. section 13.1.1














