Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate query for multiple items in a collection

Tags:

java

hibernate

I have a data model that looks something like this:

public class Item {
    private List<ItemAttribute> attributes;
    // other stuff
}

public class ItemAttribute {
    private String name;
    private String value;
}

(this obviously simplifies away a lot of the extraneous stuff)

What I want to do is create a query to ask for all Items with one OR MORE particular attributes, ideally joined with arbitrary ANDs and ORs. Right now I'm keeping it simple and just trying to implement the AND case. In pseudo-SQL (or pseudo-HQL if you would), it would be something like:

select all items
where attributes contains(ItemAttribute(name="foo1", value="bar1"))
AND attributes contains(ItemAttribute(name="foo2", value="bar2"))

The examples in the Hibernate docs didn't seem to address this particular use case, but it seems like a fairly common one. The disjunction case would also be useful, especially so I could specify a list of possible values, i.e.

where attributes contains(ItemAttribute(name="foo", value="bar1"))
OR attributes contains(ItemAttribute(name="foo", value="bar2"))
-- etc.

Here's an example that works OK for a single attribute:

return getSession().createCriteria(Item.class)
        .createAlias("itemAttributes", "ia")
        .add(Restrictions.conjunction()
            .add(Restrictions.eq("ia.name", "foo"))
            .add(Restrictions.eq("ia.attributeValue", "bar")))
        .list();

Learning how to do this would go a long ways towards expanding my understanding of Hibernate's potential. :)

like image 549
aarestad Avatar asked Jun 08 '10 20:06

aarestad


People also ask

How can I get multiple records in hibernate?

Session session = HibernateUtil. getCurrentSession(); If you want to fetch the records from a database table try this simple query: List<Object> slist = session.

How to fetch multiple entities by id with Hibernate?

Load multiple entities by their primary key class ); List<PersonEntity> persons = multiLoadAccess. multiLoad(1L, 2L, 3L); You just need to call the byMultipleIds(Class entityClass) method on the Hibernate Session and provide the class of the entities you want to load as a parameter.


1 Answers

Could you use aliasing to do this?

Criteria itemCriteria = session.createCriteria(Item.class);
itemCriteria.createAlias("itemAttributes", "ia1")
            .createAlias("itemAttributes", "ia2")
            .add(Restrictions.eq("ia1.name", "foo1"))
            .add(Restrictions.eq("ia1.attributeValue", "bar1")))
            .add(Restrictions.eq("ia2.name", "foo2"))
            .add(Restrictions.eq("ia2.attributeValue", "bar2")))

Not sure how hibernate handles joining on the same property twice explicitly like that, maybe worth trying?

like image 153
Anthony Bishopric Avatar answered Oct 03 '22 23:10

Anthony Bishopric