Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only the entity IDs in a Criteria query

I have to write a method such as public List<Integer> findIds(String someVendor) that gets only the IDs of entities matching a given property value (example, vendor).

Given this example

public class Product{
    private int id;

    private String vendor;
}

I can easily write the restriction criteria to match the vendor.

But I don't know how Criteria.list() may return Integer

return session.createCriteria(Producrt.class)
.add(Restrictions.eq("vendor",someVendor)
//What here?
.list();

Also, if I was using C#/LINQ, I would have written the following

return (from products product where product.vendor == someVendor select id).ToList();

I have never used projections in Hibernate/Java. How do I return only the IDs of matching entities into a list?

like image 309
usr-local-ΕΨΗΕΛΩΝ Avatar asked Jun 17 '13 10:06

usr-local-ΕΨΗΕΛΩΝ


1 Answers

Try below code,

sessionFactory.getCurrentSession().createCriteria(Product.class).add(
            Restrictions.eq("vendor", "vendor-value")).setProjection(Projections.property("id"))
like image 125
Pritesh Shah Avatar answered Nov 14 '22 21:11

Pritesh Shah