【问题标题】:Update generated after insert when bidirectional one to many mapping双向一对多映射时插入后生成的更新
【发布时间】:2020-11-17 04:36:26
【问题描述】:

出于性能原因,我使用双向一对多关系映射,以便在持久化实体时仅生成inserts(根据What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations? 的答案之一)

但是,当我没有在很多方面指定 CascadeType.PERSIST 时,我注意到插入后仍然会生成更新。

Hibernate: insert into promotion (deadline, description, percentage, promotion_id) values (?, ?, ?, ?)
Hibernate: update product set amount_in_stock=?, category_id=?, description=?, product_name=?, product_price=?, production_year=?, promotion_id=?, "size"=?, sold_amount=?, vendor=?, weight=? where product_id=?

Promotion可以引用很多Products:

@Entity
@Table(name = "product")
public class Product
{
    @Id
    @Column(name = "product_id")
    @SequenceGenerator(name = "product_id_sequence", sequenceName = "product_id_sequence", allocationSize = 1)
    @GeneratedValue(generator = "product_id_sequence", strategy = GenerationType.SEQUENCE)
    private Long productId;

    @ManyToOne(fetch = FetchType.LAZY) // cascade = CascadeType.PERSIST
    @JoinColumn(name = "promotion_id")
    private Promotion promotion;
   
    // setters, getters, other fields
}
@Entity
@Table(name = "Promotion")
public class Promotion
{
    @Id
    @Column(name = "PROMOTION_ID")
    @SequenceGenerator(name = "promotion_id_sequence", sequenceName = "promotion_id_sequence", allocationSize = 1)
    @GeneratedValue(generator = "promotion_id_sequence", strategy = GenerationType.SEQUENCE)
    private Long promotionId;

    @OneToMany(mappedBy = "promotion", cascade = CascadeType.ALL)
    private List<Product> products = new LinkedList<>();

    public void addProduct(Product product)
    {
        products.add(product);
        product.setPromotion(this);
    }
    // setters, getters, delete synchronization method, other fields
}

坚持逻辑(@DataJpaTest):

promotion.addProduct(product);
entityManager.persist(promotion);
entityManager.flush();

为什么会这样?

感谢阅读。

【问题讨论】:

    标签: java spring-boot hibernate one-to-many


    【解决方案1】:

    它正在发生,因为在测试中我坚持了几个与Product 有关系的实体。然后当Product 处于管理状态时,通过调用entityManager.persist(promotion); hibernate 必须通过添加promotion_id 键来更新Product

    entityManager.persist(category); // category has many products (CascadeType.ALL added)
    entityManager.persist(promotion);
    entityManager.flush();
    

    我应该提供更多的测试方法,但坦率地说我不知道​​它们有一些影响。综上所述,这不是映射的问题,而是将具有相互关系的实体持久化的顺序。最后

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "promotion_id")
    private Promotion promotion;
    

    是正确的,Product 侧不需要额外的级联。

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多