Reputation: 85
I am trying to fetch list of Users whose status still shows as inactive and process them. This User is embedded with UserDetails, UserActivity entities. All entity tables have status column with value as Inactive.
Right now I am using detached criteria as,
detachedcriteria.for class(User.class).add(Restrictions.
Eq("status","Inactive").setresulttransformer(criteria.distinct_element)
This is giving me User object along with its embedded entities as a single User object.
But now, I have to tune the query to make sure status is inactive for embedded class as well. So I did opted to go for named query as I don't know how to add multiple Restrictions for different entities in a single detached criteria.
In named query I am joining all tables to fetch the data. And I was able to get the data but its returning list of object array. Where in first object of this list contain array of below entities.
Named query:
from User us, UserDetail ud, UserActivity uc where us.id=ud.id and us.id=uc
.id and us.status=ud.status and us.status=uc.status and us.status='Inactive'
List<User>=query.list ();
Object ob=lst.get(0);
Where ob contains [User(),UserDetail(),UserActivity ()].
Can we right multiple Restrictions for different entities in a single detached criteria?
Can we have a named query which will return me a single User object along with embedded entities in it as I am getting in detachedcriteria?(So that I can directly perform User.getUserDetail()
).
Upvotes: 0
Views: 3353
Reputation: 3465
You can use aliases for this:
Assuming you have User class like
class User {
...
private UserDetail userDetail;
private UserActivity userActivity;
...
}
You can not directly put restrictions to second level properties of your object. By using .createAlias()
method you can add JOIN
statements to your generated SQL and add restrictions by using aliases.
DetachedCriteria dc = DetachedCriteria
.forClass(User.class , "u")
.add(Restrictions.Eq("u.status","Inactive")
.createAlias("u.userDetail", "ud")
.add(Restrictions.Eq("ud.status","Inactive")
.createAlias("u.userActivity", "ua")
.add(Restrictions.Eq("ua.status","Inactive")
.setResultTransformer(Criteria.DISTINCT_ROOT_ELEMENT);
Upvotes: 0