防止ManyToOne休眠中的递归关联 [英] Prevent recursive association in ManyToOne hibernate
本文介绍了防止ManyToOne休眠中的递归关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
自从在Java上与ORM合作以来,已经有一段时间了,目前正在寻找一个选项来防止在类似于OneToMany的关系中进行递归引用.这是简单的示例.
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);
}
在查询结果中, OuterEntity主机
再次包含对 InnerEntity
的引用,这些引用会启动引用.
In the result of query OuterEntity host
again contains reference on InnerEntity
which initiate reference.
常见的预防方法是什么?
What is the common approach to prevent it?
推荐答案
如果使用杰克逊,则可以使用杰克逊双向映射:
If you are using jackson you can use jacksons bidirectional mapping:
在 OuterEntity
中:
@JsonManagedReference
@OneToMany(mappedBy = "host")
private List<InnerEntity> dataset = new ArrayList<>();
在InnerEntity中:
in InnerEntity:
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
private OuterEntity host;
这篇关于防止ManyToOne休眠中的递归关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文