2016-11-23 83 views
0

如何在oneToMany關係中堅持子實體?Spring JPA + Hibernate:OneToMany雙向持久

@Entity 
public class Payment implements Serializable { 

    @ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) 
    @JoinColumn(name = "registration", nullable = false) 
    private Registration registration; 
} 

@Entity 
public class Registration implements Serializable { 

@OneToMany(mappedBy="registration", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) 
private List<Payment> payment; 
} 

在登記的創建,如果登記列不在支付表可爲空:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 列 '註冊' 不能爲空

但是,如果註冊爲空,則會創建付款,但註冊列爲空:

enter image description here

直到發生異常並且執行「HH000010:批量釋放時仍包含JDBC語句」。

請你能幫幫我,禁用Hibernate批處理或明白是什麼錯誤?

回答

0

您需要堅持註冊實體。

初始化您的報名對象

Registration reg = new Registration(); 

List<Payment> lstPayment = new ArrayList<Payment>(); 
for loop... 
    Payment pay = new Payment(); 
    // imp point 
    pay.setRegistration(reg); 
    lstPayment.add(pay); 
for loop ends // 

reg.setLstPayment(lstPayment); 

//persist Registration entity 
em.persist(reg); 
+0

我在使用帶有CrudRepository的spring boot-jpa。通常不需要指定孩子堅持。而就我而言,孩子是支付,必須堅持創建註冊 – Mezoo

0

通過查看代碼列「登記」的表登記應該是主鍵和自動遞增。如果不是這樣,請與您的桌子覈實。

如果子表的主鍵沒有設置爲主鍵並且在表中自動增量,則通過此錯誤休眠。