Select if the collection contains a particular object with Hibernate Criteria

Asked

Viewed 437 times

2

I’m trying to make a query that would be something like the method contains of interface Collection java.

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

I tried it like this and it didn’t work:

session.createCriteria(Grupo.class)
    .createAlias("produtoCollection", "produto")
    .add(Restrictions.in("produto", listaProdutos)).list();
  • The product is a Collection item or an item attribute?

  • From what I understand, you want to know if product Ollection (is a Collection right?) contains any item from a list passed as parameter?

  • Hello Dener, that’s right, I want to know if productCollection contains any product from the listProducts that was passed as parameter.

2 answers

2

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

session.createCriteria(Grupo.class)
          .createAlias("produtoCollection", "produtos")
          .add(Restrictions.in("produtos.id", "lista"));
  • At @Brunocésar edited my question, probably a moderator. I tried to use your tip but it didn’t work gave the following error: Caused by: org.postgresql.util.Psqlexception

  • Mal, my fault. Tidying up here. What does the error say exactly? It could show the classes involved in the search?

  • I got a solution using a foreach, posted in a separate reply, I do not know if it is the best way, but at the moment met the need. Thank you for your willingness to help.

1

I got a solution using a loop, I do not know if it is the best solution, but at the moment 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 doubts.

  • 1

    I had a similar problem once, which I solved based on the answer I gave you there. Anyway you can take a look at this article here http://blog.caelum.com.br/divisions-com-hibernate-uso-avancado-da-criteria-api/ I think it might help you

  • Thanks a lot, the article from Caelum was really very useful. Thanks a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.