Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL how to query ElementCollection of String

I have class like

public User{
   Long id;
   Set<String> roles;
}

How do I query all User objects with the role of "ADMIN"

EDIT:

I'm using Hibernate 3.0.5. And have tried most of the obvious approaches.

from Users where roles in('ADMIN') gives a JDBC error. from Users u where u.roles in('ADMIN') gives a class cast exception

I think this may be a problem with this particular version of hibernate.

like image 654
Thihara Avatar asked Dec 30 '12 11:12

Thihara


People also ask

How do I get a unique result from a HQL query?

HQL – Get a Unique Result. HQL’s Query interface provides a uniqueResult() method for obtaining just one object from an HQL query. Although your query may yield only one object, you may also use the uniqueResult() method with other result sets if you limit the results to just the first result.

How do you sort results in HQL?

HQL – Sorting the Results To sort your HQL query’s results, you will need to use the order by clause. You can order the results by any property on the objects in the result set: either ascending (asc) or descending (desc). You can use order on more than one property in the query if you need to.

What is a HQL query language?

HQL is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties.

Can I use an element collection instead of a @elementcollection?

I, therefore, don’t recommend to use an element collection but to instead model an association with an additional entity. If you decide to use an @ElementCollection anyways or if just can’t change the existing code, you can reference its elements similarly as you would do it with a modeled association. Let’s take a look at a simple example.


2 Answers

I've found solution:

"from User as user where 'ADMIN' in elements(user.roles)";

Somehow hql function value() have to help with this, you can also experiment with it, but that hql query above works for me.

like image 87
Skeeve Avatar answered Sep 22 '22 00:09

Skeeve


You can use the query below

"from User as user where user.id in (select user.id from Role as role left join role.user as user where role.name = 'ADMIN')"
like image 44
Roman C Avatar answered Sep 24 '22 00:09

Roman C