【问题标题】:Hibernate get entity with specific columns of nested entityHibernate获取具有嵌套实体特定列的实体
【发布时间】:2016-10-07 15:38:45
【问题描述】:

我有两个实体:

@Entity
@Table(name = "animals")
public class Animal extends BaseEntity {
    private String nickname;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "species_id", nullable = false)
    private Species species;
}

@Entity
@Table(name = "species")
public class Species extends BaseEntity {
    private String scientificName;
    private Integer animalsPerHouse;
}

如何使用特定的Species 字段获取Animal,例如scientificName?如何告诉 Hibernate 我只需要嵌套实体的特定字段?

想要的动物:

  {
    "id": 1,
    "nickname": "Locuroumee",
    "species": {
      "id": 161130,
      "scientificName": "Anguilla bicolor",
  }

实际动物:

  {
    "id": 1,
    "nickname": "Locuroumee",
    "species": {
      "id": 161130,
      "scientificName": "Anguilla bicolor",
      "animalsPerHouse": 4
  }

我已经在投影、别名上花费了很多时间,但这无济于事

【问题讨论】:

  • 我有类似的问题this

标签: hibernate projection


【解决方案1】:

此类任务有实体图。

Dynamic fetching via JPA entity graph

JPA 2.1 Entity Graph – Part 1: Named entity graphs

JPA 2.1 Entity Graph – Part 2: Define lazy/eager loading at runtime

但是,看起来,Hibernate 不支持部分字段加载,与 EclipseLink 相反。

您可以尝试使用自定义结果转换器: How to transform a flat result set using Hibernate

【讨论】:

  • 投影用于部分字段加载。它有效)它可能适用于嵌套实体字段......但我不知道如何
  • @hardcoder 请在此处查看示例:stackoverflow.com/a/36361630/3405171
  • 已经看到)他们使用自定义变压器。但显然没有它也有解决方案。
  • @hardcoder 哪个解决方案?请把它添加到问题中。如果没有变压器,使用投影,您将拥有List<Object[]>
  • 我使用 aliasToBean 转换器来避免这种情况。也许您知道如何向嵌套实体字段添加投影?
猜你喜欢
  • 2014-08-25
  • 2017-08-09
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2020-11-28
  • 2017-02-26
  • 1970-01-01
相关资源
最近更新 更多