如何从MyBatis查询返回可选参数 [英] How to return an Optional from MyBatis query

查看:362
本文介绍了如何从MyBatis查询返回可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法让MyBatis返回一个Optional<MyClass>实例而不是一个简单的MyClass实例?

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

推荐答案

Mybatis pre 3.5.0

创建自定义 ObjectFactory ,如下所示:

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);
     }
  }
}

并将其配置为在mybatis.xml中使用:

And configure it to be used in mybatis.xml:

 <objectFactory type="my.company.project.OptionalAwareObjectFactory"/>

Mybatis 3.5.0 +

自3.5.0起,Optional受本机支持,如 fankai 所指出.

Mybatis 3.5.0+

Since 3.5.0 Optional is supported natively as fankai pointed out.

这篇关于如何从MyBatis查询返回可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆