0

I have a user entity with an assistant column.

Every user has an assistant but there are circles as well.

For example : User A's assistant is User B and User B's assistant is user A.

If I use @ManyToOne and @OneToMany annotations, then, there is an infinite recursion when converting objects to JSON, even @JsonManagedReference and @JsonBackReference didn't help.

BaseEntity:

@MappedSuperclass
@Data
public class BaseEntity {

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

    @Version
    private int version;
}

User:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@Table(name = "Users")
public class User extends BaseEntity {

    @Column
    private String username;

    @Column
    private String name;

    @JsonManagedReference
    @ManyToOne
    @JoinColumn(name = "assistant_id")
    private User assistant;

    @JsonBackReference
    @OneToMany(mappedBy = "assistant")
    private Set<User> assistants;


}

Are there any opportunity in Spring to solve this?

pevad95
  • 1
  • 4

2 Answers2

0

@JsonManagedReference/@JsonBackReference won't help, because the 'forward' references can still form a cycle, even when the 'inverse' references are not being serialized.

What you want is probably for the User assigned to the assistant property to be serialized without its own assistant property (so that any cycles break). Essentially, you have the same issue as here, except in your case A and B are the same class.

Apart from the solution described in the question I've linked to, you'll also want to specify which @JsonView to use when serializing the object. See the 'Using JSON Views with Spring' section here.

crizzis
  • 9,978
  • 2
  • 28
  • 47
  • Not sure what you mean by 'work'. `assistants` are already loaded lazily by default, just like any other to-many association. Without `@JsonIgnore` Jackson still tries to serialize the property, though, trigerring the lazy loading – crizzis Sep 20 '19 at 06:28
0

Could you create Assistant entity based on the same table and join?

H Pat
  • 134
  • 5