0

(***Edited*:**I am looking for the JSON representation of the solution provided here: Spring REST multiple @RequestBody parameters, possible?)

I have the following entity Account which has a member variable of another entity called Customer

@Entity 
public class Account {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id=0;

   @ManyToOne
   @JoinColumn(name = "customer_id")
   private Customer customer;         
   ...
}

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id=0;
    private String customerId;

    public Customer(){}
    public Customer(String customerId){
      this.customerId = customerId;
    }
    public long getId(){
        return id;
    }
    public String getCustomerId(){
     return customerId;
    }
    public void setCustomerId(String customerId){
      this.customerId = customerId;
    }
  }

I need to post a JSON object representation of an Account. Here is the Controller method:

@Autowired
private AccountRepository accounts;

@RequestMapping(value="/accounts/account",method=RequestMethod.POST)
public @ResponseBody  Account addAccount(@RequestBody Account account){
     return accounts.save(account);
}

AccountRepository is an interface that extends CrudRepository

I have an existing customer with the URI http://localhost:8084/customers/customer/1

I have attempted to post the following JSON objects and received a 400 Bad Request response.

{"customer":"1"}

{"customer":"http://localhost:8084/customers/customer/1"}

{"customer":{"href":"http://localhost:8084/customers/customer/1"}}

Just to make sure that an Account can be created if correct data is received, I modified the controller method as per the following code, which created the account when I post to http://localhost:8084/accounts/account

@RequestMapping(value="/accounts/account",method=RequestMethod.POST)
public @ResponseBody  Account addAccount() throws Exception{
    Customer customer = customers.findOne(1);
    Account account = new Account();
    account.setCustomer(customer);
    return accounts.save(account);
}

So my question is, how do I format a JSON object so as to Create an Entity whose member is an existing Entity?

Community
  • 1
  • 1
Simon Savai
  • 182
  • 2
  • 13

1 Answers1

2

I found out that the correct format is to provide the URI of the referenced entity, i.e in this case it should be

{"customer":"http://localhost:8084/customers/customer/1"}

However, this only worked after I added the data-rest dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
    <version>{spri}</version>
</dependency>

Without this dependency, the request fails with a JsonMappingException

Simon Savai
  • 182
  • 2
  • 13