Explorar o código

添加公共字段插入自定义填充功能

青苗 %!s(int64=9) %!d(string=hai) anos
pai
achega
dd4e71d6ea

+ 5 - 0
mybatis-plus/src/main/java/com/baomidou/mybatisplus/MybatisConfiguration.java

@@ -50,6 +50,11 @@ public class MybatisConfiguration extends Configuration {
 	 */
 	public static ISqlInjector SQL_INJECTOR = new AutoSqlInjector();
 
+	/*
+	 * 元对象字段填充控制器
+	 */
+	public static MybatisMetaObjectHandler META_OBJECT_HANDLER = null;
+
 	/*
 	 * 是否刷新mapper
 	 */

+ 15 - 10
mybatis-plus/src/main/java/com/baomidou/mybatisplus/MybatisDefaultParameterHandler.java

@@ -58,7 +58,7 @@ public class MybatisDefaultParameterHandler extends DefaultParameterHandler {
 	 * @return
 	 */
 	protected static Object processBatch(MappedStatement ms, Object parameterObject) {
-		if ( ms.getSqlCommandType() == SqlCommandType.INSERT ) {
+		if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
 			/**
 			 * 只处理插入操作
 			 */
@@ -122,20 +122,25 @@ public class MybatisDefaultParameterHandler extends DefaultParameterHandler {
 	 *            插入数据库对象
 	 * @return
 	 */
-	protected static Object populateKeys( MappedStatement ms, Object parameterObject ) {
+	protected static Object populateKeys(MappedStatement ms, Object parameterObject) {
 		TableInfo tableInfo = TableInfoHelper.getTableInfo(parameterObject.getClass());
 		if (null != tableInfo && null != tableInfo.getIdType() && tableInfo.getIdType().getKey() >= 2) {
-			MetaObject metaParam = ms.getConfiguration().newMetaObject(parameterObject);
-			Object idValue = metaParam.getValue(tableInfo.getKeyProperty());
+			MetaObject metaObject = ms.getConfiguration().newMetaObject(parameterObject);
+			Object idValue = metaObject.getValue(tableInfo.getKeyProperty());
 			/* 自定义 ID */
-			if ( null == idValue || "".equals(idValue) ) {
-				if ( tableInfo.getIdType() == IdType.ID_WORKER ) {
-					metaParam.setValue(tableInfo.getKeyProperty(), IdWorker.getId());
-				} else if ( tableInfo.getIdType() == IdType.UUID ) {
-					metaParam.setValue(tableInfo.getKeyProperty(), get32UUID());
+			if (null == idValue || "".equals(idValue)) {
+				if (tableInfo.getIdType() == IdType.ID_WORKER) {
+					metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getId());
+				} else if (tableInfo.getIdType() == IdType.UUID) {
+					metaObject.setValue(tableInfo.getKeyProperty(), get32UUID());
 				}
 			}
-			return metaParam.getOriginalObject();
+			/* 自定义元对象填充控制器 */
+			MybatisMetaObjectHandler metaObjectHandler = MybatisConfiguration.META_OBJECT_HANDLER;
+			if (null != metaObjectHandler) {
+				metaObjectHandler.insertFill(metaObject);
+			}
+			return metaObject.getOriginalObject();
 		}
 		return parameterObject;
 	}

+ 41 - 0
mybatis-plus/src/main/java/com/baomidou/mybatisplus/MybatisMetaObjectHandler.java

@@ -0,0 +1,41 @@
+/**
+ * Copyright (c) 2011-2020, hubin (jobob@qq.com).
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.baomidou.mybatisplus;
+
+import org.apache.ibatis.reflection.MetaObject;
+
+/**
+ * <p>
+ * 元对象字段填充控制器抽象类,实现公共字段自动写入
+ * </p>
+ * 
+ * @author hubin
+ * @Date 2016-08-28
+ */
+public interface MybatisMetaObjectHandler {
+
+	/**
+	 * <p>
+	 * 插入元对象字段填充
+	 * </p>
+	 * 
+	 * @param Object
+	 *            元对象
+	 * @return
+	 */
+	void insertFill(MetaObject metaObject);
+
+}

+ 14 - 12
mybatis-plus/src/main/java/com/baomidou/mybatisplus/MybatisSessionFactoryBuilder.java

@@ -38,55 +38,57 @@ import com.baomidou.mybatisplus.mapper.ISqlInjector;
  */
 public class MybatisSessionFactoryBuilder extends SqlSessionFactoryBuilder {
 
-
 	@Override
-	public SqlSessionFactory build( Reader reader, String environment, Properties properties ) {
+	public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
 		try {
 			MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(reader, environment, properties);
 			return build(parser.parse());
-		} catch ( Exception e ) {
+		} catch (Exception e) {
 			throw ExceptionFactory.wrapException("Error building SqlSession.", e);
 		} finally {
 			ErrorContext.instance().reset();
 			try {
 				reader.close();
-			} catch ( IOException e ) {
+			} catch (IOException e) {
 				// Intentionally ignore. Prefer previous error.
 			}
 		}
 	}
 
-
 	@Override
-	public SqlSessionFactory build( InputStream inputStream, String environment, Properties properties ) {
+	public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
 		try {
 			MybatisXMLConfigBuilder parser = new MybatisXMLConfigBuilder(inputStream, environment, properties);
 			return build(parser.parse());
-		} catch ( Exception e ) {
+		} catch (Exception e) {
 			throw ExceptionFactory.wrapException("Error building SqlSession.", e);
 		} finally {
 			ErrorContext.instance().reset();
 			try {
 				inputStream.close();
-			} catch ( IOException e ) {
+			} catch (IOException e) {
 				// Intentionally ignore. Prefer previous error.
 			}
 		}
 	}
 
-	//TODO 注入数据库类型
-	public void setDbType( String dbType ) {
+	// TODO 注入数据库类型
+	public void setDbType(String dbType) {
 		MybatisConfiguration.DB_TYPE = DBType.getDBType(dbType);
 	}
 
-	//TODO 注入表字段使用下划线命名
+	// TODO 注入表字段使用下划线命名
 	public void setDbColumnUnderline(boolean dbColumnUnderline) {
 		MybatisConfiguration.DB_COLUMN_UNDERLINE = dbColumnUnderline;
 	}
 
-	//TODO 注入 SQL注入器
+	// TODO 注入 SQL注入器
 	public void setSqlInjector(ISqlInjector sqlInjector) {
 		MybatisConfiguration.SQL_INJECTOR = sqlInjector;
 	}
 
+	// TODO 注入 元对象字段填充控制器
+	public void setMetaObjectHandler(MybatisMetaObjectHandler metaObjectHandler) {
+		MybatisConfiguration.META_OBJECT_HANDLER = metaObjectHandler;
+	}
 }

+ 20 - 12
mybatis-plus/src/main/java/com/baomidou/mybatisplus/spring/MybatisSqlSessionFactoryBean.java

@@ -54,6 +54,7 @@ import org.springframework.core.io.Resource;
 import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
 
 import com.baomidou.mybatisplus.MybatisConfiguration;
+import com.baomidou.mybatisplus.MybatisMetaObjectHandler;
 import com.baomidou.mybatisplus.MybatisXMLConfigBuilder;
 import com.baomidou.mybatisplus.MybatisXMLMapperBuilder;
 import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
@@ -70,7 +71,8 @@ import com.baomidou.mybatisplus.toolkit.PackageHelper;
  * @author hubin
  * @Date 2016-01-23
  */
-public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
+public class MybatisSqlSessionFactoryBean
+		implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
 
 	private static final Log LOGGER = LogFactory.getLog(MybatisSqlSessionFactoryBean.class);
 
@@ -117,22 +119,27 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
 	private ObjectFactory objectFactory;
 
 	private ObjectWrapperFactory objectWrapperFactory;
-	
-	//TODO 注入数据库类型
+
+	// TODO 注入数据库类型
 	public void setDbType(String dbType) {
 		MybatisConfiguration.DB_TYPE = DBType.getDBType(dbType);
 	}
-	
-	//TODO 注入表字段使用下划线命名
+
+	// TODO 注入表字段使用下划线命名
 	public void setDbColumnUnderline(boolean dbColumnUnderline) {
 		MybatisConfiguration.DB_COLUMN_UNDERLINE = dbColumnUnderline;
 	}
 
-	//TODO 注入 SQL注入器
+	// TODO 注入 SQL注入器
 	public void setSqlInjector(ISqlInjector sqlInjector) {
 		MybatisConfiguration.SQL_INJECTOR = sqlInjector;
 	}
 
+	// TODO 注入 元对象字段填充控制器
+	public void setMetaObjectHandler(MybatisMetaObjectHandler metaObjectHandler) {
+		MybatisConfiguration.META_OBJECT_HANDLER = metaObjectHandler;
+	}
+
 	/**
 	 * Sets the ObjectFactory.
 	 *
@@ -432,7 +439,7 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
 
 		Configuration configuration;
 
-		//TODO 加载自定义 MybatisXmlConfigBuilder
+		// TODO 加载自定义 MybatisXmlConfigBuilder
 		MybatisXMLConfigBuilder xmlConfigBuilder = null;
 		if (this.configuration != null) {
 			configuration = this.configuration;
@@ -450,7 +457,7 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
 				LOGGER.debug(
 						"Property `configuration` or 'configLocation' not specified, using default MyBatis Configuration");
 			}
-			//TODO 使用自定义配置
+			// TODO 使用自定义配置
 			configuration = new MybatisConfiguration();
 			configuration.setVariables(this.configurationProperties);
 		}
@@ -468,7 +475,7 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
 		}
 
 		if (hasLength(this.typeAliasesPackage)) {
-			//TODO
+			// TODO
 			String[] typeAliasPackageArray = null;
 			if (typeAliasesPackage.contains("*")) {
 				typeAliasPackageArray = PackageHelper.convertTypeAliasesPackage(typeAliasesPackage);
@@ -566,9 +573,10 @@ public class MybatisSqlSessionFactoryBean implements FactoryBean<SqlSessionFacto
 				}
 
 				try {
-					//TODO
-					MybatisXMLMapperBuilder xmlMapperBuilder = new MybatisXMLMapperBuilder(mapperLocation.getInputStream(),
-							configuration, mapperLocation.toString(), configuration.getSqlFragments());
+					// TODO
+					MybatisXMLMapperBuilder xmlMapperBuilder = new MybatisXMLMapperBuilder(
+							mapperLocation.getInputStream(), configuration, mapperLocation.toString(),
+							configuration.getSqlFragments());
 					xmlMapperBuilder.parse();
 				} catch (Exception e) {
 					throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);

+ 42 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/mysql/MyMetaObjectHandler.java

@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) 2011-2020, hubin (jobob@qq.com).
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.baomidou.mybatisplus.test.mysql;
+
+import org.apache.ibatis.reflection.MetaObject;
+
+import com.baomidou.mybatisplus.MybatisMetaObjectHandler;
+
+/**
+ * <p>
+ * 测试,自定义元对象字段填充控制器,实现公共字段自动写入
+ * </p>
+ * 
+ * @author hubin
+ * @Date 2016-08-28
+ */
+public class MyMetaObjectHandler implements MybatisMetaObjectHandler {
+
+	/**
+	 * 测试 user 表 name 字段为空自动填充
+	 */
+	public void insertFill(MetaObject metaObject) {
+		Object name = metaObject.getValue("name");
+		if (null == name) {
+			metaObject.setValue("name", "instert-fill");
+		}
+	}
+
+}

+ 9 - 1
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/mysql/UserMapperTest.java

@@ -75,6 +75,11 @@ public class UserMapperTest {
          */
         mf.setSqlInjector(new MySqlInjector());
 
+        /**
+         * 设置,自定义 元对象填充器,实现公共字段自动写入
+         */
+        mf.setMetaObjectHandler(new MyMetaObjectHandler());
+
         SqlSessionFactory sessionFactory = mf.build(in);
         SqlSession session = sessionFactory.openSession();
         UserMapper userMapper = session.getMapper(UserMapper.class);
@@ -116,7 +121,10 @@ public class UserMapperTest {
         ul.add(new User(14L, "delname", 4, 0));
         ul.add(new User(15L, "5", 5, 1));
         ul.add(new User(16L, "6", 6, 0));
-        ul.add(new User(17L, "7", 7, 0));
+
+        /* 测试 name 填充 */
+        ul.add(new User(17L, 7));
+        ul.add(new User(7));
         ul.add(new User(18L, "deleteByMap", 7, 0));
 
 		/* 使用 ID_WORKER 自动生成 ID */