小编典典

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

spring-boot

我尝试使用POST方法保存实体的数组,并为其余资源传递数组,但是出现错误:

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 application / json并与text / uri-list一起使用。怎么了?我还有其他设置吗?


阅读 433

收藏
2020-05-30

共1个答案

小编典典

错误的是,它试图读取请求正文Item,而实际上是多个Items

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

您的第二个选择是手动替代一种方法来处理多个项目:http : //docs.spring.io/spring-
data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-
response-处理程序

2020-05-30