2014-05-25 5 views
1

와 JSON 개체에서 외래 키를 해결하는 방법 :(잭슨과 최대 절전 모드로) Dropwizard, 다음 클래스가 함께 책 도서관 시스템에서 잭슨

@Entity 
@Table(name="author") 
public class Author { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 

    @Column(name="name") 
    private string name; 
    // some more properties 
} 

@Entity 
@Table(name="book") 
public class Book { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 

    @Column(name="title") 
    private string title; 
    // some more properties 
} 

@POST 
public void addBook(Book book) { 
    ... 
} 

책을 추가하려면 책의 제목과 저자의 ID는 json 객체로 보내야합니다.

{"title": "Harry Potter", "author": "123"} 

그러나 Jackson이 주어진 저자 ID에서 저자를 얻을 수없는 것처럼 보입니다.

Error 400 Can not instantiate value of type [simple type] from Integral number; no single-int-arg constructor/factory method (through reference chain) 

책 개체 및 저자에 authorId에서 요청의 JSON에서 매핑을 구성하는 방법은, 당신의 책 실체가하는

class TempBook { string title; long authorId; } 

답변

2

등의 임시 객체를 생성하지 않고 있는가 "저자"속성이 없습니다. 그래서 Jackson은 JSON을 실제 Book 인스턴스로 마샬링/언 마샬링 할 수 없습니다. 내가 생각할 수있는 방법은 세터/게터 도우미 방법 같은 것을 통해 :

@OneToOne private Author authorEntity; 
public void setAuthor(String author) { this.autorEntity = new Author(author);} 

그러나 당신이 마샬링 과정에 대한 적절한 게터를 추가하고, authorEntity 속성에 대한 @JsonIgnoreProperties 주석을 사용하는 것을 고려해야합니다.

희망이 도움이됩니다.