Prevent recursive association in ManyToOne hibernate

痞子三分冷 提交于 2021-01-29 10:37:40

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/60599630/prevent-recursive-association-in-manytoone-hibernate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!