【问题标题】:SpringBoot REST - Insert Row With Foreign Key using HTTP POST JSON DataSpring Boot REST - 使用 HTTP POST JSON 数据插入具有外键的行
【发布时间】: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


【解决方案1】:
POST Test 2:  {
        "dropoff":"2017-01-30 10:33",
        "ready":"",
        "paid":"false",
        "note":"manual insert",
        "customer":{
          "id":"1"
        }
    }

测试 2 是完美的,但如果您不发送客户 ID,它将自动生成,因为您使用的是 @GeneratedValue(strategy = GenerationType.AUTO)

您必须创建一个 InvoiceRepository.java 来获取带有客户 ID 的发票,如下代码所示。

@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, Serializable>{
    Invoice findByCustomerId(long id);
}

这将返回带有特定客户 ID 的发票。

【讨论】:

    【解决方案2】:

    您需要将 URL 放入对象中,例如:

      "account" : "http://example.com/accounts/9999"
    

    在您的情况下,您可以将“帐户”替换为“客户”

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2016-03-06
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 2018-10-02
      • 2020-11-15
      • 2022-08-20
      • 1970-01-01
      相关资源
      最近更新 更多