【问题标题】:Hibernate isn't inserting foreign key ManyToOne entitiyHibernate 没有插入外键 ManyToOne 实体
【发布时间】:2019-03-01 07:48:09
【问题描述】:

我想知道为什么 Hibernate 没有将外键插入数据库。

我有 2 个类之间的 OneToMany 和 ManyToOne 关系。

@Entity
@Data
public class Bestelling {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JoinColumn(name = "bestelling_id")
    private long bestellingID;

    private Date bestelDatum;

    @ManyToOne
    @JoinColumn(name = "account_id")
    private Account accountID_fk;

    @JoinColumn(name = "adres_id")
    @OneToOne
    private Adres afleverAdres;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "bestelling")
    private List<Bestellingsregel> bestellingsregels = new ArrayList<>();
}

@Entity
@Data
public class Bestellingsregel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JoinColumn(name = "bestellingsregel_id")
    private long bestellingsregelID;

    private int aantal;
    private double prijs;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "bestelling_id")
    private Bestelling bestelling;

    @OneToOne
    @JoinColumn(name = "product_id")
    private Product productID;
}

我正在使用 Postman 将数据插入我的 MySql 数据库:

{

"bestelDatum" : "2019-02-28",
"accountID_fk" : {
                    "accountID" : 1 
                },
"afleverAdres" : {
                    "adres_id" : 1
                },
"bestellingsregels" : [
                    { "aantal" : 5,
                      "prijs" : 100.50,
                      "productID" : { "productID" : 1 }
                    }
                    ]
}

它正在向数据库中插入。唯一的问题是它没有在表 Bestellingsregel 中设置 bestelling_id。知道我在这里做错了什么吗?

提前致谢。

编辑:

我正在使用 Spring,并且 crud 函数在这个界面中:

public interface BestellingRepository extends JpaRepository<Bestelling, Long> {
}

【问题讨论】:

  • 请显示用于插入数据的java-method。
  • 亲爱的彼得。 java-methods 在 JpaRepository 中

标签: java mysql hibernate jpa


【解决方案1】:

您将 Bestelling 和 Bestellingsregel 之间的关系定义为双向与 Bestellingsregel 的拥有方(持有外键),这是正确的,但有利也有弊。

您有以下选择:

  1. 使用定义的关系并将 Bestelling 对象设置为列表中的每个 Bestellingsregel 对象。 Bestellingsregel 是拥有方,所以你必须在保存前直接设置参考。
  2. 使您的关系单向:从 Bestellingsregel 中删除 Bestelling 引用并重新定义我们的 @OneToMany 关系

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, , orphanRemoval = true)
    @JoinColumn(name = "bestelling_id")
    private List<Bestellingsregel> bestellingsregels = new ArrayList<>();
    

【讨论】:

  • 非常感谢。我使关系单向并且它起作用了。
【解决方案2】:
    Bestelling b = new Bestelling();
    Bestellingsregel br = new Bestellingsregel();
    br.setBestelling(b);
    List<Bestellingsregel> list = new ArrayList<>();
    list.add(br);
    b.setBestellingsregels(list);
    repo.save(b);

这对我有用。我猜你没有在 Bestellingsregel 对象中设置 Bestelling 对象。

【讨论】:

  • Hibernate 不应该这样做吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 2015-03-08
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多