The code snippet below lets me return person object who have or don't have a matching key/val query. For example, I can return all hairColor==red people or all people with hairColor!=red.
Code:
Criteria pCrit = sess.createCriteria(Person.class);
pCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Criteria pmCrit = tCrit.createCriteria("personMetadatas");
SimpleExpression exKey = Expression.eq("key", "hairColor");
Criteria key = pmCrit.add(exKey);
SimpleExpression exVal = Expression.eq("value", "red");
if (not)
key.add( Expression.not(exVal) );
else
key.add( exVal );
However, I cannot use this query to also return people who don't have a hairColor key at all. This next code snippet lets me return everyone who has or doesn't have a matching key query:
Code:
Criteria pCrit = sess.createCriteria(Person.class);
pCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Criteria pmCrit = tCrit.createCriteria("personMetadatas");
SimpleExpression exKey = Expression.eq("key", "hairColor");
if (not)
pmCrit.add( Expression.not(exKey) );
else
pmCrit.add( exKey );
###
What I cannot figure out is how to combine these two queries so that I can query both people hairColor!=red || don't have hairColor as an attribute.
I've tried to use an Expression.disjunction(), but cannot configure it successfully.. Here is what I tried:
Code:
Criteria aCrit = sess.createCriteria(Adaptation.class);
aCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Criteria pm = aCrit.createCriteria("personMetadatas");
Disjunction eiOr = Expression.disjunction();
pm.add( eiOr );
//restrict by key
SimpleExpression exKey = Expression.eq("key", "hairColor");
//if not, then give a chance here to prove true on no key
if (not)
{ eiOr.add( Expression.not(exKey) );
}
//then further restrict on key (here is where I suspect the problem lies)
Junction keyRestrictCrit = eiOr.add(exKey);
SimpleExpression exVal = Expression.eq("value", "red");
//and if we've got it or not
if (not)
{ keyRestrictCrit.add( Expression.not(exVal) );
}
else
{ keyRestrictCrit.add( exVal );
}
Any advice on how to successfully create a query like this? Thanks.