如何使用 Spring Boot Data Rest 在同一请求中保存多个对象 [英] How to save many objects in the same request using Spring Boot Data Rest
问题描述
我尝试使用 POST 方法保存一个实体数组,传递一个数组作为剩余资源,但我有一个错误:
I'm try save a array of an Entity using POST method passing an array for rest resource, but I have an error:
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]
我什么时候给一个对象发送数据,数据保存的很好!
When's I send one object the data, the data is saved very well!
我的实体:
@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 一起使用.怎么了?我再做一些设置?
I've tried to using the Content-Type application/json and using with text/uri-list. What is wrong? I do some more setup?
推荐答案
错误的是试图将您的请求正文作为 Item
读取,而实际上它是多个 Items代码>.
What is wrong is that is trying to read your request body as an Item
, when it is in fact multiple Items
.
我相信您在这里有两个选择.在这种情况下,我通常会做的是创建另一个资源,例如 ItemCollection
,以包装多个 Items
.然后,您可以使用标准的 REST 功能来接收 ItemCollection
,它基本上可以处理多个 Items
.
I believe you have two choices here. What I would normally do in this situation would be to create another resource, such as ItemCollection
, to wrap multiple Items
. Then you could have standard REST functionality to take in an ItemCollection
, which would essentially handle multiple Items
.
您的第二个选择是手动覆盖处理多个项目的方法:http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-响应处理程序
Your second option would be to manually override a method to handle multiple itmes: http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers
这篇关于如何使用 Spring Boot Data Rest 在同一请求中保存多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!