许多关系中的JPA 2.1高性能SaveAll

时间:2016-02-25 13:25:56

标签: hibernate jpa spring-data-jpa

我有以下实体Product(-placement)和CustomerReview with manyToMany关系。我使用带有spring-data-jpa的Hibernate来保存我的实体。

public class ProductPlacement implements Serializable{

   private static final long serialVersionUID = 1L;

   public ProductPlacement(Long id){
       this.id = id;
   }

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "product_placement_id")
   private long id;

   @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="productPlacements")
   private Set<CustomerReview> customerReviews;
}

public class CustomerReview implements Serializable{

   private static final long serialVersionUID = 1L;

   @Id
   @Column(name = "customer_review_id")
   private String reviewIdentifier;

   @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   @JoinTable(
        name = "tb_miner_review_to_product",
           joinColumns = @JoinColumn(name = "customer_review_id"),
           inverseJoinColumns = @JoinColumn(name = "product_placement_id")
        )
   private Set<ProductPlacement> productPlacements;
}

现在我正在寻找使用给定技术(Hibernate,spring-data-jpa,MySQL)的最有效方法来为ProductPlacement存储一组CustomerReviews。

void saveAllReviews (List<CustomerReview> customerReviews, long productPlacementId);

方法应该添加所有新的CustomerReviews,其中每个Review引用productPlacement并应更新现有的评论(添加对productPlacement的新引用)。

我可以在db中查询ProductPlacement,而不是从集合中查询数据库中的所有评论。对于所有现有的,我可以添加产品作为新的参考,对于所有不存在的我将创建新的对象,但这是我唯一的选择吗?或者是他们更快的方式而不首先查询产品和评论? 谢谢

更新:我从外部服务(通过邮件队列)获取评论。该消息包含其被刮过的产品(productPlacementId)和JSON格式的评论的信息。因此,我没有评论所属的整套productPlacements。下一条消息可能包含具有相同评论的新productPlacement。

因此,对于每条评论,我需要查看每条评论,如果评论已经在数据库中(通过主键);如果不是 - &gt;我需要创建一个新的Review Object并创建一个与productPlacement的关系(在此消息中);如果是 - &gt;更新现有评论(在消息中添加与productPlacement的新关系)

0 个答案:

没有答案