Hibernate不会插入外键ManyToOne实体

时间:2019-03-01 07:48:09

标签: java mysql hibernate jpa

我想知道为什么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<>();
}

AND

@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> {
}

2 个答案:

答案 0 :(得分:1)

您将Bestelling和Bestellingsregel之间的关系定义为双向的,并且在Bestellingsregel中拥有拥有方(握住外键),这是正确的,但有利有弊。

您有以下选择:

  1. 按定义使用您的关系,并将Bestelling对象设置为列表中的每个Bestellingsregel对象。 Bestellingsregel是所有者,因此您必须在保存之前直接设置参考。
  2. 使您的关系成为单向的:从Bestellingsregel中删除Bestelling参考并重新定义我们的await关系

    observer

答案 1 :(得分:0)

    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对象。

相关问题