Mybatis——MetaObject学习

简介:MetaObject是Mybatis提供的一个用于方便、优雅访问对象属性的对象,通过它可以简化代码、不需要try/catch各种reflect异常,同时它支持对JavaBean、Collection、Map三种类型对象的操作。

JavaBean:

//java bean
Object javaBean = new Example().setContent("hello");

MetaObject javaBeanMeta = MetaObject.forObject(javaBean,
                DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
System.out.println(javaBeanMeta.getValue("content"));
javaBeanMeta.setValue("content", "world");
System.out.println(javaBeanMeta.getValue("content"));
class Example {
    private String content;

    public String getContent() {
        return content;
    }

    public Example setContent(String content) {
        this.content = content;
        return this;
    }
}

运行结果:

hello
world

Collection:

//collection
List collection = new ArrayList();
MetaObject collectionMeta = MetaObject.forObject(collection,
                DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
collectionMeta.add("hello world");
System.out.println(collection.size());

运行结果:

1

Map:

//Map
Map map = new HashMap();
map.put("hello","hello world");

MetaObject mapMeta = MetaObject.forObject(map,
                DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
System.out.println(mapMeta.getValue("hello"));

运行结果:

hello world

说明:

  • 获取MetaObject对象需要使用静态方法MetaObject.forObject,并且需要指定ObjectFactory , ObjectWrapperFactory , ReflectorFactory[3.3.0之前不需要],幸运的是Mybatis为我们提供了默认实现:
    /**
     * 默认ObjectFactory
     */
    private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    /**
     * 默认ObjectWrapperFactory
     */
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    /**
     * 默认ReflectorFactory
     */
    private static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();
  • MetaObject对Collection、Map的支持并不完全,某些操作会直接抛出UnsupportedOperationException,需要注意

欢迎加群,一起学习进步

Mybatis——MetaObject学习_第1张图片

你可能感兴趣的:(Mybatis,mybatis)