Select whether the collection contains a given object with Hibernate Criteria

2

I'm trying to do a query that would be something like the contains method of the interface

I have a class Collection and I want to select the groups if your GrupoProdutos , called Collection , contains a certain product from another product list passed as a parameter.

I tried it like this and it did not work:

session.createCriteria(Grupo.class)
    .createAlias("produtoCollection", "produto")
    .add(Restrictions.in("produto", listaProdutos)).list();
    
asked by anonymous 30.06.2015 / 22:51

2 answers

2

@Resend try overwriting the "product" equals. Or you can use the primary key inside the Resricions.in like this:

session.createCriteria(Grupo.class)
          .createAlias("produtoCollection", "produtos")
          .add(Restrictions.in("produtos.id", "lista"));
    
01.07.2015 / 15:21
1

I got a solution using a loop, I do not know if it is the best solution, but at the moment it met the need:

     List<Produto> resultList = new arrayList<Produto>();

     Criteria criteria = session.createCriteria(Produto.class)
                    .createAlias("produtoCollection", "produto");
     Disjunction ou = Restrictions.disjunction();
     for(Produto p : listaProdutos){
      ou.add(Restrictions.eq("produto.id", p.getId()));
     }

     resultList = criteria.add(ou).list();

I hope you can help others with similar questions.

    
01.07.2015 / 15:37