1

Is it possible to cascade creation in Spring Data Jdbc as in Spring Data JPA for OneToMany and ManyToMany relationships? If not, what would be the strategy then ?

@Table("orders")
public class Order {
        
    @Id private UUID id;
        
    @MappedCollection(idColumn = "order_id")
    private Set<OrderItem> orderItems = new HashSet<>();
        
    private LocalDateTime lastModifiedDateTime;
        
    public Order() {}
}
@Table("orders_items")
public class OrderItem {
    
    private UUID productId;
    private Integer quantity;
    
    @Transient private Product product;
    
    public OrderItem(Product product, Integer quantity) {
        this.productId = product.getId();
        this.quantity = quantity;
    }
}
@Table("products")
public class Product {
    
    @Id private UUID id;
    private String title;
    private String description;
    private BigDecimal price;
    private LocalDateTime lastModifiedDateTime;
    
    public Product(String title, String description, BigDecimal price) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.price = price;
    }
}
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

1 Answers1

1

Is it possible to cascade creation in Spring Data JDBC[..]?

Yes and no.

Spring Data JDBC is based on the concept of aggregates. An aggregate is a cluster of objects that are tightly related and are consistent whenever you are not in a method of that aggregate. All objects in an aggregate are persisted (and loaded) together.

Everything reachable from the root object of an aggregate is considered part of an aggregate.

So in your case between Order and OrderItem which form an aggregate you do get "cascading" in a sense.

Product is a separate aggregate, and rightly so. Therefore you don't get cascading.

If not, what would be the strategy then?

There are two cases:

  1. If the id is generate during persisting, either by the database or by some event listener, just persist stuff in the right order. In this case persist the Product before you persist an Order that references it. This should become pretty obvious since the id is null before persisting the Product and you need that to reference it from the Order.

  2. If the id is generate during construction of the object you may persist aggregates in any order you like as long as your database constraints allow it. You might want to look into deferred constraints for this.

Here you can read more about aggregates in Spring Data JDBC

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348