如何使用Spring Boot Data Rest在同一请求中保存许多对象
我尝试使用POST方法保存一个实体数组,传递一个数组用于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 { }
数据:
[{ "name": "A1", "quantity": 3, "cash": 5.80 }, { "name": "B2", "quantity": 3, "cash": 5.80 }]
我尝试使用Content-Type应用程序/ json并使用text / uri-list。 怎么了? 我做了一些设置?
有什么不对的是,当它实际上是多个Items
时,它试图将你的请求主体作为一个Item
来读取。
我相信你有两个选择。 在这种情况下我通常会做的是创建另一个资源,例如ItemCollection
,以包装多个Items
。 然后,您可以使用标准RESTfunction来接收ItemCollection
,它实际上将处理多个Items
。
您的第二个选择是手动覆盖处理多个主题的方法: http : //docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-处理器