JKK
JKK

Reputation: 446

SpringBoot REST - Insert Row With Foreign Key using HTTP POST JSON Data

all.

I'm having trouble figuring out a simple problem. I have two entities in a Spring Boot application. It has a web RESTful interface. I can insert and select rows that are independent of other tables just fine, but I cannot correctly insert a row that has a foreign key. The row inserts but without the ID to link it to the parent table.

Parent table Customer:

@Entity
@Table(name = "CUSTOMER")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstname;
private String mi;
private String lastname;

...}

Child table Invoice:

@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;

...}

Here's the POST tests I've tried to send to http://localhost:8080/invoices

POST Test 1: { "dropoff":"2017-01-30 10:33", "ready":"", "paid":"false", "note":"manual insert", "customer_id":"1" }

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

POST Test 3: { "dropoff":"2017-01-30 10:33", "ready":"", "paid":"false", "note":"manual insert", "customerid":"1" }

POST Test 4: { "dropoff":"2017-01-30 10:33", "ready":"", "paid":"false", "note":"manual insert", "customerId":"1" }

When I run select on the table Invoice I see the data, but it is not associated with customer id of 1.

Interesting result: When I try POST example 2 above, it updates invoice the invoice record with id = 1. Appears to ignore the object customer inside the post package.

Not sure what format I need to follow to get invoice to be tied to customer id of 1. So far all of them insert, but without any foreign key to table Customer

Upvotes: 2

Views: 4423

Answers (2)

CIPHER007
CIPHER007

Reputation: 376

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

Test 2 is perfect but if you not sending id of customer it will automatically generate because you are using @GeneratedValue(strategy = GenerationType.AUTO)

You have to create a InvoiceRepository.java for getting invoice with customer id like below code.

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

This will return you invoice with a particular customer id.

Upvotes: 1

Dave
Dave

Reputation: 2586

You need to put the URL to the object like:

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

in your case, you'd replace "account" with "customer"

Upvotes: 1

Related Questions