0

My question is that, I have a class like:

@Entity
public class Product{
@Id
String id;
String name;
@ManyToMany
List<Tag> tags;
}

@Entity
public class Tag{
@Id
String id;
String name;
}

I want to search products with criteria like in but reversive as:

session.createCriteria(Product.class).add(
    Restrictions.and(
        Restrictions.like("name",name+"%"),
        Restrictions.contains("tags",tag)).list();

But obviously Restrictions.contains does not exist. I only can find solutions with HQL queries but I don't want to (actually can't) write HQL queries.

Is there any way to handle this with criteria?

2 Answers 2

1

I would just join the association using createAlias et do a simple compare:

session.createCriteria(Product.class)
    .createAlias("tags", "tag")
    .add( Restrictions.eq("tag", tag))
    .list()
2
  • 1
    alias is worked as expected, except it gives error when i use your code, but when i write as .add(Restrictions.eq("tag.id",tag.getId()) it worked
    – bdogru
    Mar 31, 2014 at 13:04
  • I have the same code as you @bdogru but when hibernate return the tag list, it contains only the one with the id in the condition, all other tags are not there, do you have the same issue?
    – D.T
    Jan 5, 2023 at 9:36
0

Are you are in search of Restrictions.in(String propertyName, Collection values)? In the chapter 15.2. Narrowing the result set you will find an example:

List cats = sess.createCriteria(Cat.class)
    .add(Restrictions.not(Restrictions.in("name", new String[] { "Fritz", "Izi", "Pk" })))
    .add(Restrictions.disjunction())
    .list();
3
  • No, I am in search of just the opposite of "Restrictions.in". I know what is and how to know it.
    – bdogru
    Mar 27, 2014 at 12:28
  • I added a Restrictions.not(Restrictions.in("name", new String[] { "Fritz", "Izi", "Pk" }))
    – Harmlezz
    Mar 27, 2014 at 12:38
  • It is obvious that I coulnd't made my point. My domain product has a tag list, I want to get all products that has tagList which contains a the tag.
    – bdogru
    Mar 27, 2014 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.