hibernate加载选定列

时间:2011-03-22 22:02:08

标签: hibernate

我有一张桌子: 具有列的用户:{id,name,address}

我想使用hibernate从这个表中只选择id。但我不想将HQL用于本机SQL查询。我想使用Criteria对象。有没有办法做到这一点?

谢谢,

Sean Nguyen

2 个答案:

答案 0 :(得分:4)

是。您必须使用投影:

Criteria c = session.createCriteria(User.class, "u");
c.setProjection(Projections.property("u.id"));
return c.list(); // the list of all the user IDs

但是HQL对于这种查询更具可读性和直接性。 Criteria对于动态构建的查询很有用,或者可以在多个查询中重用部分查询:

return session.createQuery("select u.id from User u").list();

答案 1 :(得分:0)

可以将ResultTransformer应用于本机SQL查询,允许它返回非托管实体。

作为一个例子,假设我们有下面的entdemodetail实体

@Entity
@Table(name = "demodetail") 
public class EntDemodetail {

    Integer id;
    String description;
    Integer demoid;
    EntDemo demo;

    @Id
    @GeneratedValue
    @Column(name = "id_detail", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="detaildesc")
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }


    @Column(name="demoid")
    public Integer getDemoid() {
        return demoid;
    }

    public void setDemoid(Integer demoid) {
        this.demoid = demoid;
    }


    @OneToOne()
    @JoinColumn(name="demoid")
    public EntDemo getDemo() {
        return demo;
    }

    public void setDemo(EntDemo demo) {
        this.demo = demo;
    }

}

您可以阅读此实体的某些列,如下所示

/* Method to  READ some columns of an entity with native sql */
       public void nativesqlwithresulttransformer( ){
          Session session = HibernateUtilMysql.getSessionFactory().openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();

             String sql = "SELECT id_detail as id FROM demodetail d"; //
             SQLQuery query = session.createSQLQuery(sql);

             List results = query.setResultTransformer(Transformers.aliasToBean(EntDemodetail.class)).list();

             for (Iterator iterator = 
                               results.iterator(); iterator.hasNext();){
                EntDemodetail entdemodetail = (EntDemodetail) iterator.next(); 
                System.out.print("Id: " + entdemodetail.getId()); 
                //System.out.print("Desc: " + entdemodetail.getDescription()); 

             }
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }

有关详细信息,请参阅http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/querysql.html