Spring Data REST:"没有用于从String值反序列化的String-argument构造函数/工厂方法"

时间:2016-12-06 02:16:29

标签: java spring java-8 spring-data-rest lombok

当我在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尝试解析应解析为单个/people/123的{​​{1}}本地URI时,会发生反序列化错误。如果我删除Person,一切正常。知道我的REST控制器定义有什么问题吗?

1 个答案:

答案 0 :(得分:11)

@RepositoryRestController中,将@RepositoryRestController参数的类型从@RequestBody 更改为Book

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

有关详细信息,请参阅Spring Data REST #687