How to return an Optional from MyBatis query

£可爱£侵袭症+ 提交于 2019-12-09 13:49:28

问题


Is there any way to get MyBatis to return an Optional<MyClass> instance rather than simply a MyClass instance?


回答1:


Mybatis pre 3.5.0

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"/>

Mybatis 3.5.0+

Since 3.5.0 Optional is supported natively as fankai pointed out.




回答2:


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.



来源:https://stackoverflow.com/questions/50214697/how-to-return-an-optional-from-mybatis-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!