我有一个对象,其中包含另一个对象的列表。 它的映射如下:
@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>();
在图像方面,这就是映射:
@Entity
@Table(name = "images")
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String url;
发生的情况是: 1. 我创建了我的产品对象并将其保存在数据库中。 2. 稍后我通过添加图片来更新此产品对象,就像这样:
Product product = repository.findById(productId);
Image image = new Image();
image.setUrl(url);
product.getImages().add(image);
repository.save(product);
每当我添加新的图片并保存时,这是我在控制台上得到的内容:
当我添加第一张图片时:
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 (?, ?)
当我添加了一张图片:
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 (?, ?)
当我添加第三张图片时:
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 (?, ?)
我的问题是:删除整个列表并将其全部重新添加到数据库中是否是正确的行为?我原本期望它只会添加新图像,保留其他图像。而实际上,它会根据产品ID删除所有图像,然后再将它们全部重新添加。
在更新产品之前,我会检索产品。 我会检索产品,将新图像添加到列表中,然后调用保存方法。
这是正常的吗?有没有避免此删除的方法?
谢谢