【发布时间】:2017-05-22 06:25:45
【问题描述】:
全部。
我无法解决一个简单的问题。我在 Spring Boot 应用程序中有两个实体。它有一个 Web RESTful 界面。我可以很好地插入和选择独立于其他表的行,但我无法正确插入具有外键的行。该行插入但没有 ID 以将其链接到父表。
父表客户:
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstname;
private String mi;
private String lastname;
...}
子表发票:
@Entity
@Table(name = "INVOICE")
public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private Date dropoff;
private Date ready;
private String note;
private Boolean paid;
private BigDecimal total_price;
private long total_quantity;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CUSTOMER_ID")
private Customer customer;
...}
这是我尝试发送到 http://localhost:8080/invoices 的 POST 测试
POST 测试 1:
{
"dropoff":"2017-01-30 10:33",
"ready":"",
"paid":"false",
"note":"manual insert",
"customer_id":"1"
}
POST 测试 2:
{
"dropoff":"2017-01-30 10:33",
"ready":"",
"paid":"false",
"note":"manual insert",
"customer":{
"id":"1"
}
}
POST 测试 3:
{
"dropoff":"2017-01-30 10:33",
"ready":"",
"paid":"false",
"note":"manual insert",
"customerid":"1"
}
POST 测试 4:
{
"dropoff":"2017-01-30 10:33",
"ready":"",
"paid":"false",
"note":"manual insert",
"customerId":"1"
}
当我在 Invoice 表上运行 select 时,我看到了数据,但它与 1 的客户 ID 没有关联。
有趣的结果:当我尝试上面的 POST 示例 2 时,它会更新 id = 1 的发票记录。似乎忽略了 post 包中的对象 customer。
不确定我需要遵循什么格式才能将发票绑定到客户 ID 1。到目前为止,所有这些都插入,但没有任何外键到表 Customer
【问题讨论】:
-
您的 spring 正在检测客户的整个对象,您可以尝试将其完整发送或将映射更改为惰性,这样您就不必在客户中发送对象而只发送它的 id。顺便说一句,这是 Hibernate 映射的问题。
-
谢谢,我试过了,结果一样。映射一直设置为惰性。哎呀,别管关于懒惰的最后一部分了。显然在上面的例子中它被设置为渴望..
标签: javascript java json hibernate spring-boot