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.
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.
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.
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.
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.
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.
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')"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With