Here is a cool thing I figured out today to use type safe property name in hibernate criteria. Typically this is done with strings, but with lambdaj, it can be done as:
..
import static ch.lambdaj.Lambda.on;
import ch.lambdaj.function.argument.Argument;
import ch.lambdaj.function.argument.ArgumentsFactory;
..
DetachedCriteria criteria = DetachedCriteria.forClass(Contract.class);
criteria.add(Restrictions.eq(propertyName(on(Contract.class).getContractKey()), 43));
...
public static String propertyName(Object placeHolder) {
Argument actualArgument = ArgumentsFactory.actualArgument(placeHolder);
return actualArgument.getInkvokedPropertyName();
}
...
Notice how the Restrictions does not take string literal and uses lambdaj to evaluate the property name from java method directly. Pretty cool ah?
Comments