2014-12-27 40 views
1

我有兩個對象:UserEntity和ApartmentEntity是關係OneToMany(一個用戶可以有很多公寓)。 (我使用@JsonManagedReference和@JsonBackReference:Infinite Recursion with Jackson JSON and Hibernate JPA issue解決了這個問題),但是現在我無法從Apartments表讀取user_id(我需要知道哪個用戶擁有當前的公寓)。如何從關係對象讀取屬性使用JsonManagedReference

ApartmentEntity:

@Entity 
@Table(name = "users") 
@Scope("session") 
public class UserEntity { 

    @Id 
    @Column(name = "user_id") 
    @GeneratedValue 
    public int user_id; 

    //other fields ... 

    @JsonManagedReference 
    @OneToMany(mappedBy="user", cascade = { CascadeType.MERGE }, fetch=FetchType.EAGER) 
    private List<ApartmentEntity> apartments; 

    //getters setters ... 
} 

ApartmentEntity

@Entity 
@Table(name = "apartments") 
public class ApartmentEntity { 

    @Id 
    @Column(name = "id") 
    @GeneratedValue 
    private int id; 

    // ... 

    @JsonBackReference 
    @ManyToOne 
    @JoinColumn(name="user_id") 
    private UserEntity user; 

    //getters, setters ... 
} 

而現在返回的JSON不具備user_id說明裏面公寓屬性。

如何解決這個問題?如何閱讀某些屬性,無論如何,使用@Json註釋。我被困在這裏。

回答

0

JsonManagedReference,JsonBackReference工作的一種方法。所以UserEntity JSON包含了ApartmentEntities,但是ApartmentEntity將不包含UserEntity。

傑克遜提供了更好的機制,以避免循環引用:

http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

既然你已經使用JPA的id字段,我會建議對實體類使用PropertyGenerator:

@JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class,property =「user_id」,scope = UserEntity.class)

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerat or.class,property =「id」,scope = ApartmentEntity.class)