What the common behaviour when updating an unidirectional @OneToMany List of objects with Spring Data-JPA?
Asked Answered
A

1

11

I have an Object with a List of another object. It's mapped like this:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "products")
public class Product extends DateAudit {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Size(min = 3, max = 30)
    private String name;

    @NotBlank
    private String shortDescription;

    @NotBlank
    private String description;

    @NotNull
    private Double regularPrice;

    private Double promotionPrice;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id", nullable = false)
    private Category category;

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "store_id", nullable = false)
    private Store store;

    @Size(max = 20)
    private String sku;

    private Double weight;

    private Integer quantityInStock;

    @NotNull
    private Boolean notifyLowStock;

    @OneToMany(cascade = CascadeType.ALL)
    private List<Image> images = new ArrayList<Image>();

On the Image side, that's the maaping:

@Entity
@Table(name = "images")
public class Image {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    private String url;

What happens is: 1. I create my Product object and save it on the database. 2. I update this product object by adding images to it later like this:

Product product = repository.findById(productId);
Image image = new Image();
image.setUrl(url);
product.getImages().add(image);
repository.save(product);

This is what I get on my console everytime I add a new image to the product and save it:

When I add the first image:

2018-07-27 22:46:47.367 DEBUG 8580 --- [nio-5000-exec-3] org.hibernate.SQL                        : insert into images (url) values (?)
2018-07-27 22:46:48.307 DEBUG 8580 --- [nio-5000-exec-3] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)

When I add one more image:

2018-07-27 22:47:09.955 DEBUG 8580 --- [nio-5000-exec-4] org.hibernate.SQL                        : delete from products_images where product_id=?
2018-07-27 22:47:09.957 DEBUG 8580 --- [nio-5000-exec-4] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)
2018-07-27 22:47:09.958 DEBUG 8580 --- [nio-5000-exec-4] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)

When I add the third image:

2018-07-27 22:47:32.314 DEBUG 8580 --- [nio-5000-exec-5] org.hibernate.SQL                        : delete from products_images where product_id=?
2018-07-27 22:47:32.316 DEBUG 8580 --- [nio-5000-exec-5] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)
2018-07-27 22:47:32.318 DEBUG 8580 --- [nio-5000-exec-5] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)
2018-07-27 22:47:32.319 DEBUG 8580 --- [nio-5000-exec-5] org.hibernate.SQL                        : insert into products_images (product_id, images_id) values (?, ?)

My question is: Is deleting the whole list and adding all of it back to the database the correct behaviour? I was expecting it do just add the new image, leaving the other images there. Instead if remove all images based on the productId and the add it all back again.

I retrieve the product right before updating it. I retrieve the product, I add the new image to the list and I call the save method.

Is that normal? Is there a way to avoid this delete?

Thanks

Asuncionasunder answered 28/7, 2018 at 5:50 Comment(6)
Don't describe your code. Post it.Entangle
Are you added the image into List<Image> of product, and image.set(product)Kweilin
No. It's an unidirectional OneToMany. Which means that Product know the image, but image doesn't know the product.Asuncionasunder
@JBNizet, I updated the question adding the code.Asuncionasunder
@Asuncionasunder you've added the code you used to replicate the expected behavior, but not the unexpected behavior. That would be helpful.Weston
The behaviour that is happening is that every time I add a new image, it removes everything and add the list back (with new ids). I was expecting it to just add the new image without deleting the others. If you take a look on the log I pasted, you'll see that before adding, it deletes everything from the products_images table and then add 2 items. Even though I had just added one. It deletes everything, add the existing one and then add the new one.Asuncionasunder
M
5

In short, this needs either an order in the list, e.g. by Image.url:

@OneToMany(cascade = CascadeType.ALL)
@OrderColumn(name = "url")
private List<Image> images = new ArrayList<>();

or don't worry about the order:

@OneToMany(cascade = CascadeType.ALL)
private Set<Image> images = new HashSet<>();

Either of those eliminates the delete and extra insert against products_images.

The nearest thing I know of to a high-level explanation of this is here, though it's talking about @Embeddable instead of @Entity elements in the collection. It seems like Hibernate should have less issue identifying individual entities (with ids) in a collection, but it doesn't do this for an unsorted List (or PersistentBag in the Hibernate model).

Mary answered 10/8, 2018 at 19:25 Comment(1)
Thanks! That solved my problem. The @OrderColumn on List<Image> still doing some weird stuff. It doesn't delete the whole list anymore, but it tries to update the id of the others. Using Set it works perfectly.Asuncionasunder

© 2022 - 2024 — McMap. All rights reserved.