【问题标题】:Spring Entity OneToMany Ignore SelfSpring Entity OneToMany 忽略自我
【发布时间】:2018-04-04 23:23:28
【问题描述】:

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

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

更新实体时一切正常。但是,当我尝试检索所有培训师时,它会在口袋妖怪中包含培训师,这是我不想要的。观察:

GET ALL 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
            }
        }
    ]
}

注意训练师类是如何在口袋妖怪集合内的每个口袋妖怪中返回的?我不想返回它,因为我已经可以访问该信息。无论如何我可以告诉实体不要从口袋妖怪类返回自己的信息吗?如果有帮助,我的检索查询如下所示:

public List<Trainer> getAllTrainers() {
    em.getTransaction().begin();
    List<Trainer> trainer = em.createNativeQuery("SELECT * FROM
    Trainer", Trainer.class).getResultList();
    em.getTransaction().commit();
    return trainer;
}

非常感谢。

【问题讨论】:

  • 你有 FetchType.EAGER - 试试 LAZY
  • 我试过了,但我得到“无法懒惰地初始化角色集合”错误。有什么建议吗?

标签: java spring hibernate entity


【解决方案1】:

对于任何感兴趣的人,我可以通过 @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<>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-25
    • 2021-05-06
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多