Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for entities where list contains any value from list in java hibernate

Lets imagine that I have some Product entity with java.List of tags, as blelow:

@Entity
public class Product impements Serializable{
   ...
   private List<String> tags;
}

and I have user, that wants to search for products tagged (for example) by any of tags: Car, Motocycle, Plane.

so when it comes to search i have list of tags in my entity, and list of search tags, where all i need is to have at least one of them it in my product's tags list. I don't know how to write such query. thx for help

like image 869
Misiakw Avatar asked Feb 01 '13 11:02

Misiakw


2 Answers

before beny23 posted his solution i fixed it by adding

SELECT p FROM Product p, IN (p.tags) t where t in (:searchList)

but his answer is also correct.

like image 50
Misiakw Avatar answered Sep 22 '22 06:09

Misiakw


You can do this using the following HQL query:

session.createQuery("from Product p join p.tags t where t = :tag")
       .setString("tag", tagToSearchFor)
like image 20
beny23 Avatar answered Sep 25 '22 06:09

beny23