如何使用JsonManagedReference从关系对象中读取属性

时间:2014-12-27 14:59:25

标签: java json spring hibernate jpa

我有两个对象:与OneToMany相关的UserEntity和ApartmentEntity(一个用户可以有很多公寓)。 我有问题,使用无限递归将其序列化为JSON(我使用@JsonManagedReference和@JsonBackReference:Infinite Recursion with Jackson JSON and Hibernate JPA issue解决了它),但现在我无法从Apartments表中读取user_id(我需要知道哪个用户拥有当前的公寓) )。

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在Apartment属性中没有user_id。

如何解决这个问题?无论如何,使用@Json注释阅读某些属性。我被困在这里。

1 个答案:

答案 0 :(得分:0)

JsonManagedReference,JsonBackReference以一种方式工作。所以UserEntity JSON包含ApartmentEntities,但ApartmentEntity不包含UserEntity。

杰克逊提供了一种更好的机制来避免循环引用:

http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

由于您已经有一个使用JPA的id字段,我建议在实体类上使用PropertyGenerator:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =&#34; user_id&#34;,scope = UserEntity.class)

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =&#34; id&#34;,scope = ApartmentEntity.class)