0

It was a while since a worked with ORM on Java and currently looking for an option prevent recursive references in OneToMany-like relationships. Here is trivial sample.

@Entity
public class InnerEntity extends BaseEntity {

    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private OuterEntity host;

    public InnerEntity() {
    }

    public InnerEntity(String name, OuterEntity host) {
        this.name = name;
        this.host = host;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OuterEntity getHost() {
        return host;
    }

    public void setHost(OuterEntity host) {
        this.host = host;
    }

}

@Entity
public class OuterEntity extends BaseEntity {

    private String name;

    @OneToMany(mappedBy = "host")
    private List<InnerEntity> dataset;

    public OuterEntity() {
    }

    public OuterEntity(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<InnerEntity> getDataset() {
        return dataset;
    }

    public void setDataset(List<InnerEntity> dataset) {
        this.dataset = dataset;
    }
}

public interface OuterTestRepository extends CrudRepository<OuterEntity, Long> {

    @Query("SELECT outerEntity FROM OuterEntity outerEntity LEFT JOIN outerEntity.dataset")
    Collection<OuterEntity> getAll();
}

@GetMapping("/test")
public ResponseEntity<?> validate() {
    return new ResponseEntity<>(repository.getAll(), HttpStatus.OK);
}

In the result of query OuterEntity host again contains reference on InnerEntity which initiate reference.

What is the common approach to prevent it?

Gleichmut
  • 5,953
  • 5
  • 24
  • 32

1 Answers1

2

If you are using jackson you can use jacksons bidirectional mapping:

in OuterEntity:

@JsonManagedReference
@OneToMany(mappedBy = "host")
private List<InnerEntity> dataset = new ArrayList<>();

in InnerEntity:

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
private OuterEntity host;
Nonika
  • 2,490
  • 13
  • 15