简体   繁体   中英

Hibernate detached criteria for multiple Restrictions

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 ()].
  1. Can we right multiple Restrictions for different entities in a single detached criteria?

  2. 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() ).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM