hibernatequery-by-example

Query by Example on associations


It's very frustrating that you cannot use QBE on associations.

I have a large datatable with about 8 many-to-one columns. There is a a drop-down list for every column to filter the table.

Let's assume the following:

Table User

User { id, UserStatus, UserAuthorization }

I want to use this code:

Criteria crit = getSession().createCriteria(class);
crit.add(Example.create(userObject));

This does not work on the following example userObject:

User id=1 { UserStatus=Active, UserAuthorization=Admin }

because QBE doesn't support collections.

One way to solve this is to use it this way:

crit.createCriteria("UserStatus").add(Example.create(userStatusObject));
crit.createCriteria("UserAuthorization").add(Example.create(userAuthorizationObject));

My question is how this can be programmed dynamically just with the given User object. Is there another way than using QBE?


Solution

  • you can combine QBE and normal Expressions to handle the parts QBE doesnt support

    Criteria crit = getSession().createCriteria(class);
        .add(Example.create(userObject));
        .add(Expression.eq("UserStatus", userObject.getUserStatus()));