使用Spring Boot,如何发布代表其成员是另一个实体的实体的JSON对象

时间:2014-11-04 15:47:58

标签: json rest spring-boot restful-url

(***编辑*:**我正在寻找此处提供的解决方案的JSON表示:Spring REST multiple @RequestBody parameters, possible?

我有以下实体帐户,其中有一个名为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;
    }
  }

我需要发布一个帐户的JSON对象表示。这是Controller方法:

@Autowired
private AccountRepository accounts;

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

AccountRepository是一个扩展CrudRepository

的接口

我的现有客户的URI为http://localhost:8084/customers/customer/1

我试图发布以下JSON对象并收到400 Bad Request响应。

{"customer":"1"}

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

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

为了确保在收到正确的数据时可以创建帐户,我根据以下代码修改了控制器方法,该代码在我发布到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);
}

所以我的问题是,如何格式化JSON对象以创建其成员是现有实体的实体?

1 个答案:

答案 0 :(得分:2)

我发现正确的格式是提供被引用实体的URI,即在这种情况下它应该是

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

然而,这仅在我添加数据依赖依赖

之后才有效
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
    <version>{spri}</version>
</dependency>

如果没有此依赖关系,请求将失败并显示JsonMappingException