Spring Entity OneToMany忽略自我

时间:2018-04-04 23:23:29

标签: java spring hibernate entity

目前,我在两个实体之间存在以下关系:

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

更新实体时一切都很好。但是,当我尝试检索所有训练师时,它包括口袋妖怪中的训练师,这是我不想要的。观察:

获得所有POKEMON(一切都很好):

{
    "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;
}

非常感谢你。

1 个答案:

答案 0 :(得分:0)

对于任何有兴趣的人,我都可以通过告诉我的Trainer类通过@JsonIgnoreProperties忽略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<>();