【问题标题】:With Spring Boot, how to post JSON object that represents an entity whose member is another entity使用 Spring Boot,如何发布代表其成员是另一个实体的实体的 JSON 对象
【发布时间】:2014-12-31 14:08:09
【问题描述】:

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

我有以下实体 Account,它有另一个名为 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 对象表示。这是控制器方法:

@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 对象以创建其成员是现有实体的实体?

【问题讨论】:

    标签: json rest spring-boot restful-url


    【解决方案1】:

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

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

    但是,这仅在我添加了 data-rest 依赖项后才有效

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

    如果没有这种依赖关系,请求将失败并返回 JsonMappingException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多