How to use hibernate criteria to return only one element of an object instead the entire object?

一世执手 提交于 2019-11-29 04:46:07

问题


I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?

An example :

final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
    .append( bob.class.getName() ).append( " bob " )
    .append( "where bob.id > 10");

final Query query = session.createQuery( hql.toString() );
return query.list();

回答1:


I think you could do that with Projections, something like

Criteria.forClass(bob.class.getName())
        .add(Restrictions.gt("id", 10))
        .setProjection(Projections.property("id"))
        );



回答2:


Similarly you can also:

Criteria criteria = session.createCriteria(bob.class);

criteria.add(Expression.gt("id", 10));

criteria.setProjection(Projections.property("id"));

criteria.addOrder(Order.asc("id"));

return criteria.list();



回答3:


or setProjection(Projections.id())




回答4:


http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/2/




回答5:


SessionFactory sessionFactory;    
Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.setProjection(Projections.property("id"));
List result = crit.list();

This code code will give you list of ids in the model class like [1,2,3]. if you wants to get the array list like [{"id":1},{"id":2}] then use the following code

SessionFactory sessionFactory;    
Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class); 
crit.setProjection(Projections.property("id").as("id")); 
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();



回答6:


Another option (though a bit un hibernate-esque) is to use "raw" sql, like this:

List<Long> myList = session.createSQLQuery("select single_column from table_name")
          .addScalar("single_column", StandardBasicTypes.LONG).list();



回答7:


You can do that like this

    bob bb=null;

    Criteria criteria = session.createCriteria(bob.class);  
    criteria.add(Restrictions.eq("id",id));

    bb = (bob) criteria.uniqueResult();

as Restrictions you can add your condition



来源:https://stackoverflow.com/questions/58561/how-to-use-hibernate-criteria-to-return-only-one-element-of-an-object-instead-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!