如何使用休眠查询仅获取具有关联的实体的某些字段? [英] How to fetch only some fields of an entity having associations using hibernate query?

查看:62
本文介绍了如何使用休眠查询仅获取具有关联的实体的某些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个字段的实体,其中一些是关联.假设该实体具有与以下相似的结构:

I have an entity which has multiple fields, some of which are associations. Assume the entity has similar structure to the following:

@Entity
@Table(name="foos")
public class Foo {

  public Foo() {}
  @Id
  private Long id;

  @Column
  private String name;

  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "bar_id")
  private Bar bar;

  @ManyToOne
  @JoinColumn(name = "bar1_id")
  private Bar1 bar1;

  @ManyToOne
  @JoinColumn(name = "bar2_id")
  private Bar2 bar2;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
  @JoinColumn(name = "foo_id")
  private List<Bar3> bar3;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
  @JoinColumn(name = "foo_id")
  private List<Bar4> bar4;

  //getters and setters
}

我的问题是使用Hibernate查询如何只加载某些字段而不加载整个实体?
我只想获取id,bar,bar1和bar3,并且不想获取创建的Foo对象中的其余字段(名称,bar2,bar4).我是Hibernate的新手,所以任何建议都将不胜感激.

My question is how can I load only some fields and not the whole entity using Hibernate query?
I want to fetch only id, bar, bar1 and bar3, and don't want to fetch the remaining fields(name, bar2, bar4) in the created Foo object.
I'm pretty new to Hibernate so any advice will be appreciated.

推荐答案

借助以下

I was able to solve the problem with the help of the following link. I've created a new entity FooShort, with the same table name "foos", and containing only the fields required from Foo.

@Entity
@Table(name="foos")
public class FooShort {

  public FooShort() {}
  @Id
  private Long id;

  @OneToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "bar_id")
  private Bar bar;

  @ManyToOne
  @JoinColumn(name = "bar1_id")
  private Bar1 bar1;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
  @JoinColumn(name = "foo_id")
  private List<Bar3> bar3;

  //getters and setters
}

这篇关于如何使用休眠查询仅获取具有关联的实体的某些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆