【问题标题】:How to make Hibernate criteria to bring only needed fields如何使 Hibernate 标准只带来需要的字段
【发布时间】:2014-04-05 18:48:06
【问题描述】:

我有下一堂课:

@Entity
@Table(name="A")
public class A implements Serializable{

    @Id
    @Column(name="a_id")
    private long aId;

    @ManyToOne
    @JoinColumn(name="b_id")    
    private B b;
}

@Entity
@Table(name="b")
public class B implements Serializable{

    @Id
    @Column(name="b_id")
    private long bId;

    @Column(name="b_name")
    private String name;

    @Column(name="b_age")
    private String age;

    @OneToMany(mappedBy="b")
    private Set<A> a;        
}

我有这个类的 getter 和 setter。

当我尝试执行下一个标准时

session.createCriteria(A.class, "a_table")
             .createAlias("a_table.b", "b_table")
             .add(Restrictions.eq("b_table.age", "11"))
             .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
             .list();

在休眠生成的 SQL 中,我有来自 B 的所有字段(我的意思也是字段“名称”)。 我怎样才能让 Hibernate 只带来需要的字段。

如果条件中存在多个表的多个别名,则可能会增加执行时间。 谢谢。

【问题讨论】:

    标签: java sql hibernate


    【解决方案1】:

    尝试使用投影。也许是这样的:

    Criteria cr = session.createCriteria(User.class)
    .setProjection(Projections.projectionList()
      .add(Projections.property("id"), "id")
      .add(Projections.property("Name"), "Name"))
    .setResultTransformer(Transformers.aliasToBean(User.class));
    

    列表列表 = cr.list();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2012-01-15
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      相关资源
      最近更新 更多