Hibernate query for multiple items in a collection

后端 未结 5 631
灰色年华
灰色年华 2021-02-14 01:24

I have a data model that looks something like this:

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

public class Item         


        
相关标签:
5条回答
  • 2021-02-14 01:39

    I didn't test it, but this is how I should try to solve your problem if I would have to:

    Map<String,String> map1 = new TreeMap<String,String>();  
    map1.put("ia.name","foo1");  
    map1.put("ia.value","bar1");  
    Map<String,String> map2 = new TreeMap<String,String>();  
    map2.put("ia.name","foo2");  
    map2.put("ia.value","bar2");  
    return getSession().createCriteria(Item.class)
    .createAlias("itemAttributes", "ia")
    .add(Restrictions.and()
         .add(Restrictions.allEq(map1))
         .add(Restrictions.allEq(map2))
    )
    .list();
    

    Please, let me know if it worked. I think the same should work with or()...

    0 讨论(0)
  • 2021-02-14 01:44

    Use LEFT_OUTER_JOIN to prevent "WHERE x = 1 AND x = 2" kind of issue

    CreateAlias("itemAttributes", "ia", JoinType.LEFT_OUTER_JOIN)

    0 讨论(0)
  • 2021-02-14 01:47

    Why wouldn't the following work?

    return getSession().createCriteria(Item.class)
        .createAlias("itemAttributes", "ia")
        .add(Restrictions.or()
            .add(Restrictions.conjunction()
                .add(Restrictions.eq("ia.name", "foo1"))
                .add(Restrictions.eq("ia.attributeValue", "bar1")))
            .add(Restrictions.conjunction()
                .add(Restrictions.eq("ia.name", "foo2"))
                .add(Restrictions.eq("ia.attributeValue", "bar2"))))
        .list();
    

    That would be (name=foo1 && attributeValue=bar1) OR (name=foo2 && attributeValue=bar2)

    0 讨论(0)
  • 2021-02-14 02:01

    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?

    0 讨论(0)
  • 2021-02-14 02:02
    SELECT item FROM Item item JOIN item.attributes attr 
        WHERE attr IN (:attrList) GROUP BY item
    

    and then in the Java code:

    List<ItemAttribute> attrList = new ArrayList<ItemAttribute>();
    attrList.add(..); // add as many attributes as needed
    ...// create a Query with the above string
    query.setParameter("attrList", attrList);
    
    0 讨论(0)
提交回复
热议问题