编辑:我在两个类中都使用@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中有两个实体。口袋妖怪,其具有";"类型";pokemon具有的和具有列表"的Type;pokemon";具有特定类型的。我试图在我的控制器中实现一个getAll方法,但我遇到了一个无限递归问题。
我试着在我的类型类中使用@JsonIgnore注释,但这样我就无法获得每个类型中的pokemon列表。关系的另一面运作良好。
有没有什么方法可以避免无限递归问题,同时获得两个关系列表。
我的存储库扩展了JpaRepository,而我的控制器只调用JpaRepository的findAll方法。
口袋妖怪:
@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: ...,
},
.
.
.
]
我建议使用com.fasterxml.jackson.annotation
包中的@JsonManagedReference
@JsonBackReference
(后者将用于子实体(。
这里还解释了:https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion第3节
从类型表中删除Id的getter也可以使用