如何使用Spring Boot Data Rest在同一请求中保存多个对象

时间:2016-11-01 15:04:22

标签: java spring spring-boot spring-data-rest

我尝试使用POST方法保存一个Entity数组,传递一个数组用于rest资源,但是我有一个错误:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of br.com.servtech.almox.model.Item out of START_ARRAY token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@2af1e451; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of br.com.servtech.almox.model.Item out of START_ARRAY token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@2af1e451; line: 1, column: 1]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:228) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readInternal(AbstractJackson2HttpMessageConverter.java:205) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]

当我向一个对象发送数据时,数据保存得非常好!

我的实体:

@Entity
public class Item implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Basic
    private String name;

    @Basic
    private Integer quantity;

    @Basic
    private Double cash;

    @ManyToOne
    private Requirement requirement;

    //getters and setters
}

我的存储库:

@RepositoryRestResource
@CrossOrigin
public interface ItemDAO extends CrudRepository<Item, Long> {

}

数据:

[{ 
    "name": "A1", 
    "quantity": 3, 
    "cash": 5.80
}, { 
    "name": "B2", 
    "quantity": 3, 
    "cash": 5.80
}]

我尝试使用Content-Type应用程序/ json并使用text / uri-list。 怎么了?我做了一些设置吗?

1 个答案:

答案 0 :(得分:2)

有问题的是,当您的请求正文实际上是多个s时,它会尝试将您的请求正文读取为Item

我相信你有两个选择。在这种情况下我通常会做的是创建另一个资源,例如Items,以包装多个ItemCollection。然后,您可以使用标准REST功能来接收Items,这实际上将处理多个ItemCollection

您的第二个选择是手动覆盖处理多个主题的方法:http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers