Is there any way to get MyBatis to return an Optional<MyClass>
instance rather than simply a MyClass
instance?
Create custom ObjectFactory like this:
class OptionalAwareObjectFactory extends DefaultObjectFactory {
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
if (Optional.class.isAssignableFrom(type)) {
return Optional.fromNullable(Iterables.getOnlyElement(constructorArgs));
} else {
return super.create(type, constructorArgTypes, constructorArgs);
}
}
}
And configure it to be used in mybatis.xml
:
<objectFactory type="my.company.project.OptionalAwareObjectFactory"/>
Since 3.5.0 Optional
is supported natively as fankai pointed out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With