有什么方法可以让MyBatis返回Optional<MyClass>
实例而不是简单的MyClass
实例吗?
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.
Mybatis supports Optional return type officially now since 3.5.0, refer to http://blog.mybatis.org/2019/01/mybatis-350-released.html
Not sure how Roman's answer worked ... it might work in earlier version of Mybatis, as the method signature suggests, but apparently doesn't work with latest versions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.