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?
Try below code,
sessionFactory.getCurrentSession().createCriteria(Product.class).add(
Restrictions.eq("vendor", "vendor-value")).setProjection(Projections.property("id"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With