[ACCEPTED]-How to use hibernate criteria to return only one element of an object instead the entire object?-criteria
Accepted answer
I think you could do that with Projections, something 1 like
Criteria.forClass(bob.class.getName())
.add(Restrictions.gt("id", 10))
.setProjection(Projections.property("id"))
);
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();
0
or setProjection(Projections.id())
0
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 3 in the model class like [1,2,3]
.
if you wants to 2 get the array list like [{"id":1},{"id":2}]
then use the following 1 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();
Another option (though a bit un hibernate-esque) is 1 to use "raw" sql, like this:
List<Long> myList = session.createSQLQuery("select single_column from table_name")
.addScalar("single_column", StandardBasicTypes.LONG).list();
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.