防止 ManyToOne hibernate 中的递归关联

Prevent recursive association in ManyToOne hibernate

在 Java 上使用 ORM 已经有一段时间了,目前正在寻找一个选项来防止类似 OneToMany 的关系中的递归引用。这是简单的示例。

@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);
}

在查询结果中 OuterEntity host 再次包含对 InnerEntity 的引用,该引用启动引用。

常见的预防方法是什么?

如果您使用的是 jackson,则可以使用 jackson 双向映射:

OuterEntity中:

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

在内部实体中:

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