1

I've got two objects: UserEntity and ApartmentEntity that are relationed OneToMany (one user can have many apartments). I had problem with serializing it into JSON with infinite recursion ( I solved it using @JsonManagedReference and @JsonBackReference: Infinite Recursion with Jackson JSON and Hibernate JPA issue ), but now i can't read user_id from Apartments table (i need to know which user own current apartment).

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

And now returned JSON don't have user_id inside Apartment attributes.

How to solve this problem? How to read some attribute anyway, using that @Json annotations. I'm stuck here.

Community
  • 1
  • 1
zeus
  • 51
  • 1
  • 5

1 Answers1

0

JsonManagedReference, JsonBackReference work one way. So UserEntity JSON contains ApartmentEntities, but ApartmentEntity won't contain UserEntity.

Jackson provides a better mechanism to avoid circular references:

http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

Since you already have an id field using JPA, I would recommend using PropertyGenerator on the entity classes:

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

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