How to use sleep criteria to return only one element of an object, and not the entire object?

I am trying to get only the id list of the bob object, for example, instead of the bob list. This is fine with an HQL query, but I would know if criteria can be used?

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(); 
+34
hibernate criteria
Sep 12 '08 at 9:33
source share
7 answers

I think you could do it with Projections, something like

 Criteria.forClass(bob.class.getName()) .add(Restrictions.gt("id", 10)) .setProjection(Projections.property("id")) ); 
+45
Sep 12 '08 at 10:28
source share

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(); 
+18
Jun 15 '13 at 22:12
source share

or setProjection (Projections.id ())

+8
Sep 12 '08 at 13:52
source share
+3
Apr 23 '09 at 11:02
source share
 SessionFactory sessionFactory; Criteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class); crit.setProjection(Projections.property("id")); List result = crit.list(); 

This code will give you a list of identifiers in the model class, for example [1,2,3] . if you want to get a list of arrays, for example, [{"id":1},{"id":2}] , 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(); 
+2
Aug 21 '19 at 4:05
source share

Another option (although the un hibernate-esque bit) is to use "raw" sql, for example:

 List<Long> myList = session.createSQLQuery("select single_column from table_name") .addScalar("single_column", StandardBasicTypes.LONG).list(); 
+1
Apr 16 '15 at 18:30
source share

You can do it like that

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

as limitations you can add your condition

-one
May 13 '16 at 6:43 a.m.
source share



All Articles