当前位置: 首页 > 知识库问答 >
问题:

Spring Data REST:“没有从字符串值反序列化的字符串参数构造函数/工厂方法”

许涵容
2023-03-14

当我在Spring Data REST应用程序中使用Lombok来定义复杂类型时,例如:

@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;

    // ...
}

使用Spring Data REST控制器,例如:

@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);
    }
}

我遇到了一个可怕的错误:

no String-argument constructor/factory method to deserialize from String value

来自Spring Data REST使用Jackson和Book POST,例如:

curl -X POST 
     -H 'content-type: application/json' 
     -d '{"title":"Skip Like a Pro", "author": "/people/123"}'
     http://localhost:8080/api/books/

当Jackson试图解析本地URI时,会发生反序列化错误,该URI应解析为单个唯一的人。如果我删除我的RepositoryRestController,一切正常。知道我的REST控制器定义有什么问题吗?

共有1个答案

宫坚
2023-03-14

@RepositoryRestController中,将@Request estBody参数的类型从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()
        // ...
    }

并且在实体定义中,将AllArgsConstructor注释修改为:@AllArgsConstructor(suppressConstructorProperties=true)

有关更多信息,请参阅Spring Data REST#687。

 类似资料: