【问题标题】:How to read attribute from relationed object using JsonManagedReference如何使用 JsonManagedReference 从相关对象中读取属性
【发布时间】:2014-12-27 14:59:25
【问题描述】:

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

公寓实体:

@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 ...
}

公寓实体

@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 注释读取某些属性。我被困在这里了。

【问题讨论】:

    标签: java json spring hibernate jpa


    【解决方案1】:

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

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

    http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

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

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

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = ApartmentEntity.class)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多