001/** 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.table; 017 018import org.apache.ibatis.reflection.MetaObject; 019import org.apache.ibatis.reflection.property.PropertyTokenizer; 020import org.apache.ibatis.reflection.wrapper.BeanWrapper; 021import org.apache.ibatis.reflection.wrapper.ObjectWrapper; 022import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; 023 024import java.util.Collection; 025import java.util.Map; 026 027public class EntityWrapperFactory implements ObjectWrapperFactory { 028 029 @Override 030 public boolean hasWrapperFor(Object object) { 031 Class<?> objectClass = object.getClass(); 032 if (Map.class.isAssignableFrom(objectClass) || 033 Collection.class.isAssignableFrom(objectClass)) { 034 return false; 035 } 036 return TableInfoFactory.ofEntityClass(objectClass) != null; 037 } 038 039 @Override 040 public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) { 041 return new FlexBeanWrapper(metaObject, object); 042 } 043 044 static class FlexBeanWrapper extends BeanWrapper { 045 046 private Object entity; 047 private TableInfo tableInfo; 048 049 public FlexBeanWrapper(MetaObject metaObject, Object object) { 050 super(metaObject, object); 051 this.entity = object; 052 this.tableInfo = TableInfoFactory.ofEntityClass(object.getClass()); 053 } 054 055 @Override 056 public void set(PropertyTokenizer prop, Object value) { 057 Object v = tableInfo.invokeOnSetListener(entity, prop.getName(), value); 058 super.set(prop, v); 059 } 060 } 061}