Spring Data REST:“没有String-argument构造函数/工厂方法从String值反序列化” [英] Spring Data REST: "no String-argument constructor/factory method to deserialize from String value"
问题描述
当我在Spring Data REST应用程序中使用Lombok来定义复杂类型时:
When I use Lombok in my Spring Data REST application to define complex types like:
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "BOOK")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Long id;
private String title;
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
private Person author;
// ...
}
春天数据REST控制器如:
with a Spring Data REST controllers like:
@RepositoryRestController
public class BookRepositoryRestController {
private final BookRepository repository;
@Autowired
public BookRepositoryRestController(BookRepository repository) {
this.repository = repository;
}
@RequestMapping(method = RequestMethod.POST,value = "/books")
public @ResponseBody PersistentEntityResource post(
@RequestBody Book book,
PersistentEntityResourceAssembler assembler) {
Book entity = processPost(book);
return assembler.toResource(entity);
}
private Book processPost(Book book) {
// ...
return this.repository.save(book);
}
}
我收到一个丑陋的错误:
I get an ugly error:
no String-argument constructor/factory method to deserialize from String value
来自Spring Data REST的
使用Jackson与Book POST一样:
from Spring Data REST's use of Jackson with a Book POST like:
curl -X POST
-H 'content-type: application/json'
-d '{"title":"Skip Like a Pro", "author": "/people/123"}'
http://localhost:8080/api/books/
反序列化错误发生在Jackson尝试解析 / people / 123
本地URI,该URI应解析为单个唯一的 Person
。如果我删除 @RepositoryRestController
,一切正常。知道我的REST控制器定义有什么问题吗?
The de-serialization error happens when Jackson tries to resolve the /people/123
local URI which should resolve to a single, unique Person
. If I remove my @RepositoryRestController
, everything works fine. Any idea what's wrong with my REST controller definition?
推荐答案
在 @RepositoryRestController
,将 @RequestBody
参数的类型从 Book
更改为资源< ;预订>
:
In the @RepositoryRestController
, change the type of the @RequestBody
argument from Book
to Resource<Book>
:
import org.springframework.hateoas.Resource;
// ...
@RequestMapping(method = RequestMethod.POST,value = "/books")
public @ResponseBody PersistentEntityResource post(
@RequestBody Resource<Book> bookResource, // Resource<Book>
PersistentEntityResourceAssembler assembler) {
Book book = bookResource.getContent()
// ...
}
以及 Book
实体定义将 AllArgsConstructor
注释修改为: @AllArgsConstructor(suppressConstructorProperties = true)
。
and in the Book
entity definition modify the AllArgsConstructor
annotation to be: @AllArgsConstructor(suppressConstructorProperties = true)
.
有关详细信息,请参阅 Spring Data REST#687 。
See Spring Data REST #687 for more information.
这篇关于Spring Data REST:“没有String-argument构造函数/工厂方法从String值反序列化”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!