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

7

37

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();
Chartism answered 12/9, 2008 at 9:33 Comment(0)
M
47

I think you could do that with Projections, something like

Criteria.forClass(bob.class.getName())
        .add(Restrictions.gt("id", 10))
        .setProjection(Projections.property("id"))
        );
Microscope answered 12/9, 2008 at 10:28 Comment(0)
P
20

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();
Poul answered 15/6, 2013 at 22:12 Comment(0)
A
8

or setProjection(Projections.id())

Anemometer answered 12/9, 2008 at 13:52 Comment(0)
L
2
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();
Lancewood answered 21/8, 2019 at 4:5 Comment(0)
P
1

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();
Presnell answered 16/4, 2015 at 18:30 Comment(0)
B
-1

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

Broderickbrodeur answered 13/5, 2016 at 6:43 Comment(1)
Is not the answer to the question, but it was usuful to meTherewith

© 2022 - 2024 — McMap. All rights reserved.