Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
rotsch Avatar asked Feb 16 '12 10:02

rotsch


2 Answers

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()));
like image 178
Firo Avatar answered Oct 14 '22 06:10

Firo


Here's a generic answer that I found worked for me inside of my repository base, using reflection:

protected T GetByExample(T example)
{
    var c = DetachedCriteria.For<T>().Add(Example.Create(example).ExcludeNone());
    var props = typeof (T).GetProperties()
        .Where(p => p.PropertyType.GetInterfaces().Contains(typeof(IEntityBase)));
    foreach (var pInfo in props)
    {
        c.Add(Restrictions.Eq(pInfo.Name, pInfo.GetValue(example)));
    }
    return Query(c);
}

Note that all of my entities inherit from IEntityBase, which allowed me to find just those foreign key references from the object properties so I could add them to the criteria. You'll have to provide some way to execute the query (i.e. c.GetExecutableCriteria(Session))

like image 33
6utt3rfly Avatar answered Oct 14 '22 05:10

6utt3rfly