目前,我在两个实体之间具有以下关系:
@Entity
public class Pokemon {
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "trainer_id")
@JsonIgnoreProperties("pokemons")
private Trainer trainer;
}
还有:
@Entity
public class Trainer {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER,
mappedBy = "trainer")
private Set<Pokemon> pokemons = new HashSet<>();
}
更新实体时一切正常。但是,当我尝试检索所有训练师时,它会将训练师包含在口袋妖怪中,这是我不想要的。观察:
获取所有神奇宝贝(一切都很好):
{
"id": 1,
"name": "squirtle",
"type": "water",
"trainer": {
"id": 1,
"name": "Ash Ketchum",
"level": 1
}
}
获取所有培训师:
{
"id": 1,
"name": "Ash Ketchum",
"level": 1,
"pokemons": [
{
"id": 1,
"name": "squirtle",
"type": "water",
"trainer": {
"id": 1,
"name": "Ash Ketchum",
"level": 1
}
}
]
}
注意神奇宝贝集合中每个神奇宝贝的训练师类别是如何返回的吗?我不想退回该信息,因为我已经可以访问该信息。无论如何,我可以告诉实体不要从 Pokemon 类返回自己的信息吗?如果有帮助的话,我的检索查询如下所示:
public List<Trainer> getAllTrainers() {
em.getTransaction().begin();
List<Trainer> trainer = em.createNativeQuery("SELECT * FROM
Trainer", Trainer.class).getResultList();
em.getTransaction().commit();
return trainer;
}
非常感谢。
最佳答案
对于任何感兴趣的人,我可以通过 @JsonIgnoreProperties 告诉我的 Trainer 类忽略 Pokemon 对象中的 trainer 属性来实现我的目标
@Entity
public class Trainer implements Serializable {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "trainer")
@JsonIgnoreProperties(value = "trainer")
private Set<Pokemon> pokemons = new HashSet<>();
关于java - Spring实体OneToMany忽略自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49661883/