为什么 hibernate 为 OneToMany 映射生成插入和更新 [英] Why hibernate generates insert and update for OneToMany mapping

查看:28
本文介绍了为什么 hibernate 为 OneToMany 映射生成插入和更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过一个小例子来理解 Hibernate 中的一对多映射.我有一个 Product 和一组 Part's.这是我的实体类:

I am trying to understand the one-to-many mapping in Hibernate with a small example. I have a Product with a set of Part's. Here are my entity classes:

Part.java

@Entity
public class Part {
    @Id
    @GeneratedValue
    int id;
    String partName;
    //Setters & Getters
}

Product.java

@Entity
public class Product {
    private String serialNumber;
    private Set<Part> parts = new HashSet<Part>();
    @Id
    public String getSerialNumber() {
        return serialNumber;
    }
    @OneToMany
    @JoinColumn(name = "PRODUCT_ID")
    public Set<Part> getParts() {
        return parts;
    }
    // Setter methods
}

然后我尝试在我的数据库中保存一些零件和产品,并观察到以下由 hibernate 生成的查询:

Then I tried to save some parts and products in my database and observed below queries generated by hibernate:

Hibernate: insert into Product (serialNumber) values (?)
Hibernate: insert into Part (partName, id) values (?, ?)
Hibernate: update Part set PRODUCT_ID=? where id=?

这里要在Part表中添加一条记录,hibernate会生成2个DML操作——insertupdate.如果单个 insert 命令足以在表中添加一条记录,那么为什么在这种情况下 hibernate 同时使用插入和更新?请解释.

Here to add a record in Part table, hibernate generates 2 DML operations - insert and update. If a single insert command is sufficient to add a record in table then why hibernate uses both insert and update in this case? Please explain.

推荐答案

我知道这太老了,但我遇到了同样的问题,谷歌把我带到了这里,所以在修复它之后我想我应该发布一个答案.

I know this is crazy old but I had the same problem and Google brought me here, so after fixing it I figured I should post an answer.

如果您使连接列不可为空且不可更新,Hibernate 会将插入/更新方法切换为直接插入,我认为在您的情况下无论如何都不是:

Hibernate will switch the insert/update approach to straight inserts if you make the join column not nullable and not updatable, which I assume in your case it is neither anyways:

@JoinColumn(name = "PRODUCT_ID", nullable = false, updatable = false)

这篇关于为什么 hibernate 为 OneToMany 映射生成插入和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆