Getting only the entity IDs in a Criteria query
Asked Answered
M

1

5

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?

Memory answered 17/6, 2013 at 10:17 Comment(0)
C
7

Try below code,

sessionFactory.getCurrentSession().createCriteria(Product.class).add(
            Restrictions.eq("vendor", "vendor-value")).setProjection(Projections.property("id"))
Chevaldefrise answered 17/6, 2013 at 10:26 Comment(2)
AFAIK it's supposed to return List<Product>. I'm going to debug that in half an hourYorktown
No, that worked. I've successfully obtained a List<Integer> from that query!!Yorktown

© 2022 - 2024 — McMap. All rights reserved.