编辑:我在两个类中都使用了@JsonIgnoreProperties解决了这个问题
@JsonIgnoreProperties("pokemons")
@ManyToMany
@JoinTable(
name = "pokemon_types",
joinColumns = @JoinColumn(name = "pokemon_id"),
inverseJoinColumns = @JoinColumn(name = "type_id"))
private Set<Type> types;
@JsonIgnoreProperties("types")
@ManyToMany(mappedBy = "types")
Set<Pokemon> pokemons;
我的api中有两个实体。口袋妖怪具有口袋妖怪具有的“类型”的列表,而类型有口袋妖怪具有该特定类型的“口袋妖怪”的列表。我正在尝试在控制器中实现getAll方法,但遇到了无限递归问题。
我尝试在我的类型类中使用@JsonIgnore注释,但与此同时,我无法获取每种类型内的神奇宝贝列表。冲突的另一面效果很好。
有什么方法可以避免无限递归问题,并同时获得双方的冲突清单。
我的存储库扩展了JpaRepository,我的控制器仅调用JpaRepository的findAll方法。
Pokemon:
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="pokemons")
public class Pokemon implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String url;
private String img;
@ManyToMany
@JoinTable(
name = "pokemon_types",
joinColumns = @JoinColumn(name = "pokemon_id"),
inverseJoinColumns = @JoinColumn(name = "type_id"))
private Set<Type> types;
}
类型:
@Setter @Getter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="types")
public class Type implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@JsonIgnore
@ManyToMany(mappedBy = "types")
Set<Pokemon> pokemons;
}
预期结果:
[
{
id: ...,
name: ...,
pokemons: [
{
id: ...,
name; ...
url: ...
img: ...
},
.
.
.
]
},
.
.
.
]
实际结果:
[
{
id: ...,
name: ...,
},
.
.
.
]
答案 0 :(得分:0)
我建议使用@JsonManagedReference
包中的@JsonBackReference
com.fasterxml.jackson.annotation
(稍后将在子实体上使用)。
也在此处进行了解释:https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion第3节
答案 1 :(得分:0)
从类型表中删除ID的吸气剂也将起作用