Ver Fonte

Merge branch 'dev'

Caratacus há 8 anos atrás
pai
commit
b4361f7eb0

+ 411 - 0
mybatis-plus/src/main/java/com/baomidou/mybatisplus/MybatisSqlSessionTemplate.java

@@ -0,0 +1,411 @@
+/**
+ *    Copyright 2010-2016 the original author or authors.
+ *
+ *    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 com.baomidou.mybatisplus.exceptions.MybatisPlusException;
+import org.apache.ibatis.cursor.Cursor;
+import org.apache.ibatis.executor.BatchResult;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.ExecutorType;
+import org.apache.ibatis.session.ResultHandler;
+import org.apache.ibatis.session.RowBounds;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.mybatis.spring.MyBatisExceptionTranslator;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.dao.support.PersistenceExceptionTranslator;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.sql.Connection;
+import java.util.List;
+import java.util.Map;
+
+import static java.lang.reflect.Proxy.newProxyInstance;
+import static org.springframework.util.Assert.notNull;
+
+/**
+ * Copy SqlSessionTemplate
+ * 
+ * @see org.mybatis.spring.SqlSessionTemplate
+ */
+public class MybatisSqlSessionTemplate implements SqlSession, DisposableBean {
+
+	private final SqlSessionFactory sqlSessionFactory;
+
+	private final ExecutorType executorType;
+
+	private final SqlSession sqlSessionProxy;
+
+	private final PersistenceExceptionTranslator exceptionTranslator;
+
+	/**
+	 * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
+	 * provided as an argument.
+	 *
+	 * @param sqlSessionFactory
+	 */
+	public MybatisSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
+		this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
+	}
+
+	/**
+	 * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}
+	 * provided as an argument and the given {@code ExecutorType}
+	 * {@code ExecutorType} cannot be changed once the
+	 * {@code SqlSessionTemplate} is constructed.
+	 *
+	 * @param sqlSessionFactory
+	 * @param executorType
+	 */
+	public MybatisSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
+		this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration()
+				.getEnvironment().getDataSource(), true));
+	}
+
+	/**
+	 * Constructs a Spring managed {@code SqlSession} with the given
+	 * {@code SqlSessionFactory} and {@code ExecutorType}. A custom
+	 * {@code SQLExceptionTranslator} can be provided as an argument so any
+	 * {@code PersistenceException} thrown by MyBatis can be custom translated
+	 * to a {@code RuntimeException} The {@code SQLExceptionTranslator} can also
+	 * be null and thus no exception translation will be done and MyBatis
+	 * exceptions will be thrown
+	 *
+	 * @param sqlSessionFactory
+	 * @param executorType
+	 * @param exceptionTranslator
+	 */
+	public MybatisSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
+			PersistenceExceptionTranslator exceptionTranslator) {
+
+		notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
+		notNull(executorType, "Property 'executorType' is required");
+
+		this.sqlSessionFactory = sqlSessionFactory;
+		this.executorType = executorType;
+		this.exceptionTranslator = exceptionTranslator;
+		this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),
+				new Class[] { SqlSession.class }, new SqlSessionInterceptor());
+	}
+
+	public SqlSessionFactory getSqlSessionFactory() {
+		return this.sqlSessionFactory;
+	}
+
+	public ExecutorType getExecutorType() {
+		return this.executorType;
+	}
+
+	public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
+		return this.exceptionTranslator;
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> T selectOne(String statement) {
+		return this.sqlSessionProxy.<T> selectOne(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> T selectOne(String statement, Object parameter) {
+		return this.sqlSessionProxy.<T> selectOne(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
+		return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
+		return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
+		return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> Cursor<T> selectCursor(String statement) {
+		return this.sqlSessionProxy.selectCursor(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> Cursor<T> selectCursor(String statement, Object parameter) {
+		return this.sqlSessionProxy.selectCursor(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) {
+		return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <E> List<E> selectList(String statement) {
+		return this.sqlSessionProxy.<E> selectList(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <E> List<E> selectList(String statement, Object parameter) {
+		return this.sqlSessionProxy.<E> selectList(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
+		return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void select(String statement, ResultHandler handler) {
+		this.sqlSessionProxy.select(statement, handler);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void select(String statement, Object parameter, ResultHandler handler) {
+		this.sqlSessionProxy.select(statement, parameter, handler);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
+		this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int insert(String statement) {
+		return this.sqlSessionProxy.insert(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int insert(String statement, Object parameter) {
+		return this.sqlSessionProxy.insert(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int update(String statement) {
+		return this.sqlSessionProxy.update(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int update(String statement, Object parameter) {
+		return this.sqlSessionProxy.update(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int delete(String statement) {
+		return this.sqlSessionProxy.delete(statement);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public int delete(String statement, Object parameter) {
+		return this.sqlSessionProxy.delete(statement, parameter);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public <T> T getMapper(Class<T> type) {
+		return getConfiguration().getMapper(type, this);
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void commit() {
+		throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void commit(boolean force) {
+		throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void rollback() {
+		throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void rollback(boolean force) {
+		throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void close() {
+		throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public void clearCache() {
+		this.sqlSessionProxy.clearCache();
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public Configuration getConfiguration() {
+		return this.sqlSessionFactory.getConfiguration();
+	}
+
+	/**
+	 * {@inheritDoc}
+	 */
+
+	public Connection getConnection() {
+		return this.sqlSessionProxy.getConnection();
+	}
+
+	/**
+	 * {@inheritDoc}
+	 *
+	 * @since 1.0.2
+	 */
+
+	public List<BatchResult> flushStatements() {
+		return this.sqlSessionProxy.flushStatements();
+	}
+
+	/**
+	 * Allow gently dispose bean:
+	 * <p>
+	 * 
+	 * <pre>
+	 * {@code
+	 * 
+	 * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
+	 *  <constructor-arg index="0" ref="sqlSessionFactory" />
+	 * </bean>
+	 * }
+	 * </pre>
+	 * <p>
+	 * The implementation of {@link DisposableBean} forces spring context to use
+	 * {@link DisposableBean#destroy()} method instead of
+	 * {@link MybatisSqlSessionTemplate#close()} to shutdown gently.
+	 *
+	 * @see MybatisSqlSessionTemplate#close()
+	 * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary
+	 * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME
+	 */
+
+	public void destroy() throws Exception {
+		// This method forces spring disposer to avoid call of
+		// SqlSessionTemplate.close() which gives UnsupportedOperationException
+	}
+
+	/**
+	 * Proxy needed to route MyBatis method calls to the proper SqlSession got
+	 * from Spring's Transaction Manager It also unwraps exceptions thrown by
+	 * {@code Method#invoke(Object, Object...)} to pass a
+	 * {@code PersistenceException} to the
+	 * {@code PersistenceExceptionTranslator}.
+	 */
+	private class SqlSessionInterceptor implements InvocationHandler {
+
+		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+			SqlSession sqlSession = MybatisSqlSessionTemplate.this.sqlSessionFactory
+					.openSession(MybatisSqlSessionTemplate.this.executorType);
+			try {
+				Object result = method.invoke(sqlSession, args);
+				sqlSession.commit(true);
+				return result;
+			} catch (Throwable t) {
+				throw new MybatisPlusException(t);
+			} finally {
+				if (sqlSession != null) {
+					sqlSession.close();
+				}
+			}
+		}
+	}
+}

+ 4 - 2
mybatis-plus/src/main/java/com/baomidou/mybatisplus/activerecord/Model.java

@@ -39,9 +39,11 @@ import java.util.Map;
  * @param <T>
  * @Date 2016-11-06
  */
-@SuppressWarnings({ "serial", "rawtypes" })
+@SuppressWarnings({ "rawtypes" })
 public abstract class Model<T extends Model> implements Serializable {
 
+	private static final long serialVersionUID = 1L;
+
 	/**
 	 * <p>
 	 * 插入
@@ -327,7 +329,7 @@ public abstract class Model<T extends Model> implements Serializable {
 	public int selectCount(Wrapper wrapper) {
 		Map<String, Object> map = new HashMap<String, Object>();
 		map.put("ew", wrapper);
-		return SqlHelper.retCount(sqlSession().<Integer> selectOne(sqlStatement(SqlMethod.SELECT_COUNT), map));
+		return SqlHelper.retCount(sqlSession().<Integer>selectOne(sqlStatement(SqlMethod.SELECT_COUNT), map));
 	}
 
 	/**

+ 2 - 14
mybatis-plus/src/main/java/com/baomidou/mybatisplus/entity/GlobalConfiguration.java

@@ -15,6 +15,7 @@
  */
 package com.baomidou.mybatisplus.entity;
 
+import com.baomidou.mybatisplus.MybatisSqlSessionTemplate;
 import com.baomidou.mybatisplus.enums.DBType;
 import com.baomidou.mybatisplus.enums.FieldStrategy;
 import com.baomidou.mybatisplus.enums.IdType;
@@ -30,10 +31,8 @@ import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
 import org.apache.ibatis.logging.Log;
 import org.apache.ibatis.logging.LogFactory;
 import org.apache.ibatis.session.Configuration;
-import org.apache.ibatis.session.ExecutorType;
 import org.apache.ibatis.session.SqlSession;
 import org.apache.ibatis.session.SqlSessionFactory;
-import org.mybatis.spring.SqlSessionTemplate;
 
 import javax.sql.DataSource;
 import java.io.Serializable;
@@ -92,8 +91,6 @@ public class GlobalConfiguration implements Cloneable, Serializable {
 	private Set<String> mapperRegistryCache = new ConcurrentSkipListSet<String>();
 	// 单例重用SqlSession
 	private SqlSession sqlSession;
-	// 批量SqlSession
-	private SqlSession sqlsessionBatch;
 
 	public GlobalConfiguration() {
 		// 构造方法
@@ -186,8 +183,7 @@ public class GlobalConfiguration implements Cloneable, Serializable {
 
 	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
 		this.sqlSessionFactory = sqlSessionFactory;
-		this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
-		this.sqlsessionBatch = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
+		this.sqlSession = new MybatisSqlSessionTemplate(sqlSessionFactory);
 	}
 
 	public boolean isCapitalMode() {
@@ -216,10 +212,6 @@ public class GlobalConfiguration implements Cloneable, Serializable {
 		return sqlSession;
 	}
 
-	public SqlSession getSqlsessionBatch() {
-		return sqlsessionBatch;
-	}
-
 	@Override
 	protected GlobalConfiguration clone() throws CloneNotSupportedException {
 		return (GlobalConfiguration) super.clone();
@@ -365,10 +357,6 @@ public class GlobalConfiguration implements Cloneable, Serializable {
 		return getGlobalConfig(configuration).getSqlSession();
 	}
 
-	public static SqlSession getSqlsessionBatch(Configuration configuration) {
-		return getGlobalConfig(configuration).getSqlsessionBatch();
-	}
-
 	/**
 	 * 设置元数据相关属性
 	 *

+ 19 - 6
mybatis-plus/src/main/java/com/baomidou/mybatisplus/mapper/AutoSqlInjector.java

@@ -811,7 +811,8 @@ public class AutoSqlInjector implements ISqlInjector {
 	public void injectSqlRunner(Configuration configuration) {
 		this.configuration = configuration;
 		this.languageDriver = configuration.getDefaultScriptingLanguageInstance();
-		initSelect();
+		initSelectList();
+		initSelectObjs();
 		initInsert();
 		initUpdate();
 		initDelete();
@@ -873,19 +874,31 @@ public class AutoSqlInjector implements ISqlInjector {
 	}
 
 	/**
-	 * initSelect
+	 * initSelectList
 	 */
-	private void initSelect() {
-		if (hasMappedStatement(SqlRunner.SELECT)) {
+	private void initSelectList() {
+		if (hasMappedStatement(SqlRunner.SELECT_LIST)) {
 			logger.warn("MappedStatement 'SqlRunner.Select' Aalready Exists");
 			return;
 		}
 		SqlSource sqlSource = languageDriver.createSqlSource(configuration, SqlRunner.SQLScript, Map.class);
-		createSelectMappedStatement(SqlRunner.SELECT, sqlSource, Map.class);
+		createSelectMappedStatement(SqlRunner.SELECT_LIST, sqlSource, Map.class);
 	}
 
 	/**
-	 * initSelect
+	 * initSelectObjs
+	 */
+	private void initSelectObjs() {
+		if (hasMappedStatement(SqlRunner.SELECT_OBJS)) {
+			logger.warn("MappedStatement 'SqlRunner.Select' Aalready Exists");
+			return;
+		}
+		SqlSource sqlSource = languageDriver.createSqlSource(configuration, SqlRunner.SQLScript, Object.class);
+		createSelectMappedStatement(SqlRunner.SELECT_OBJS, sqlSource, Object.class);
+	}
+
+	/**
+	 * initCount
 	 */
 	private void initCount() {
 		if (hasMappedStatement(SqlRunner.COUNT)) {

+ 5 - 8
mybatis-plus/src/main/java/com/baomidou/mybatisplus/mapper/SqlHelper.java

@@ -64,25 +64,22 @@ public class SqlHelper {
 	 * @return SqlSession
 	 */
 	public static SqlSession sqlSessionBatch(Class<?> clazz) {
-		SqlSession sqlSession = getSqlSession(clazz, true);
-		return (sqlSession != null) ? sqlSession : GlobalConfiguration.currentSessionFactory(clazz).openSession(
-				ExecutorType.BATCH, false);
+		return GlobalConfiguration.currentSessionFactory(clazz).openSession(
+				ExecutorType.BATCH);
 	}
 
 	/**
 	 * 获取sqlSessionå
 	 *
 	 * @param clazz
-	 * @param isBatch
 	 * @return
 	 */
-	private static SqlSession getSqlSession(Class<?> clazz, boolean isBatch) {
+	private static SqlSession getSqlSession(Class<?> clazz) {
 		SqlSession session = null;
 		try {
 			SqlSessionFactory sqlSessionFactory = GlobalConfiguration.currentSessionFactory(clazz);
 			Configuration configuration = sqlSessionFactory.getConfiguration();
-			GlobalConfiguration globalConfiguration = GlobalConfiguration.getGlobalConfig(configuration);
-			session = isBatch ? globalConfiguration.getSqlsessionBatch() : globalConfiguration.getSqlSession();
+			session= GlobalConfiguration.getGlobalConfig(configuration).getSqlSession();
 		} catch (Exception e) {
 			// ignored
 		}
@@ -101,7 +98,7 @@ public class SqlHelper {
 	 * @return SqlSession
 	 */
 	public static SqlSession sqlSession(Class<?> clazz, boolean autoCommit) {
-		SqlSession sqlSession = getSqlSession(clazz, false);
+		SqlSession sqlSession = getSqlSession(clazz);
 		return (sqlSession != null) ? sqlSession : GlobalConfiguration.currentSessionFactory(clazz).openSession(autoCommit);
 	}
 

+ 12 - 3
mybatis-plus/src/main/java/com/baomidou/mybatisplus/mapper/SqlRunner.java

@@ -41,7 +41,8 @@ public class SqlRunner {
 	public static final String INSERT = "com.baomidou.mybatisplus.mapper.SqlRunner.Insert";
 	public static final String DELETE = "com.baomidou.mybatisplus.mapper.SqlRunner.Delete";
 	public static final String UPDATE = "com.baomidou.mybatisplus.mapper.SqlRunner.Update";
-	public static final String SELECT = "com.baomidou.mybatisplus.mapper.SqlRunner.Select";
+	public static final String SELECT_LIST = "com.baomidou.mybatisplus.mapper.SqlRunner.SelectList";
+	public static final String SELECT_OBJS = "com.baomidou.mybatisplus.mapper.SqlRunner.SelectObjs";
 	public static final String COUNT = "com.baomidou.mybatisplus.mapper.SqlRunner.Count";
 	public static final String SQLScript = "${sql}";
 	public static final String SQL = "sql";
@@ -87,7 +88,15 @@ public class SqlRunner {
 	}
 
 	public List<Map<String, Object>> selectList(String sql, Object... args) {
-		return sqlSession().selectList(SELECT, sqlMap(sql, args));
+		return sqlSession().selectList(SELECT_LIST, sqlMap(sql, args));
+	}
+
+	public List<Object> selectObjs(String sql, Object... args) {
+		return sqlSession().selectList(SELECT_OBJS, sqlMap(sql, args));
+	}
+
+	public Object selectObj(String sql, Object... args) {
+		return SqlHelper.getObject(selectObjs(sql, args));
 	}
 
 	public int selectCount(String sql, Object... args) {
@@ -103,7 +112,7 @@ public class SqlRunner {
 		if (null == page) {
 			return null;
 		}
-		page.setRecords(sqlSession().selectList(SELECT, sqlMap(sql, args), page));
+		page.setRecords(sqlSession().selectList(SELECT_LIST, sqlMap(sql, args), page));
 		return page;
 	}
 

+ 202 - 194
mybatis-plus/src/main/java/com/baomidou/mybatisplus/plugins/PerformanceInterceptor.java

@@ -1,194 +1,202 @@
-/**
- * Copyright (c) 2011-2014, 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.plugins;
-
-import java.text.DateFormat;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-import java.util.Properties;
-
-import org.apache.ibatis.executor.Executor;
-import org.apache.ibatis.mapping.BoundSql;
-import org.apache.ibatis.mapping.MappedStatement;
-import org.apache.ibatis.mapping.ParameterMapping;
-import org.apache.ibatis.plugin.Interceptor;
-import org.apache.ibatis.plugin.Intercepts;
-import org.apache.ibatis.plugin.Invocation;
-import org.apache.ibatis.plugin.Plugin;
-import org.apache.ibatis.plugin.Signature;
-import org.apache.ibatis.reflection.MetaObject;
-import org.apache.ibatis.session.Configuration;
-import org.apache.ibatis.session.ResultHandler;
-import org.apache.ibatis.session.RowBounds;
-import org.apache.ibatis.type.TypeHandlerRegistry;
-
-import com.baomidou.mybatisplus.entity.CountOptimize;
-import com.baomidou.mybatisplus.entity.GlobalConfiguration;
-import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
-import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
-import com.baomidou.mybatisplus.plugins.pagination.Pagination;
-import com.baomidou.mybatisplus.toolkit.SqlUtils;
-import com.baomidou.mybatisplus.toolkit.SystemClock;
-
-/**
- * <p>
- * 性能分析拦截器,用于输出每条 SQL 语句及其执行时间
- * </p>
- * 
- * @author hubin nieqiurong
- * @Date 2016-07-07
- */
-@Intercepts({
-		@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
-				RowBounds.class, ResultHandler.class }),
-		@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
-public class PerformanceInterceptor implements Interceptor {
-
-	/**
-	 * SQL 执行最大时长,超过自动停止运行,有助于发现问题。
-	 */
-	private long maxTime = 0;
-
-	private boolean format = false;
-	/**
-	 * count 优化方式
-	 */
-	private String optimizeType = "default";
-
-	public Object intercept(Invocation invocation) throws Throwable {
-		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
-		Object parameterObject = invocation.getArgs()[1];
-		RowBounds rowBounds = null;
-		Pagination pagination = null;
-		boolean isPageSql = false;
-		if (invocation.getMethod().getName().equals("query")) {
-			rowBounds = (RowBounds) invocation.getArgs()[2];
-			if (rowBounds instanceof Pagination) {
-				isPageSql = true;
-				Pagination page = (Pagination) rowBounds;
-				pagination = new Pagination(page.getCurrent(), page.getLimit());
-			}
-		}
-		BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
-		Configuration configuration = mappedStatement.getConfiguration();
-		StringBuilder sqlBuilder = new StringBuilder();
-		if (isPageSql) {
-			Pagination page = (Pagination) rowBounds;
-			boolean orderBy = true;
-			String dbType = GlobalConfiguration.getDbType(configuration).getDb();
-			if (page.isSearchCount()) {
-				CountOptimize countOptimize = SqlUtils.getCountOptimize(boundSql.getSql(), optimizeType, dbType,
-						page.isOptimizeCount());
-				orderBy = countOptimize.isOrderBy();
-			}
-			String sql = DialectFactory.buildPaginationSql(pagination,
-					SqlUtils.concatOrderBy(boundSql.getSql(), page, orderBy), dbType, null).replaceAll("[\\s]+", " ");
-			sqlBuilder.append(getSql(configuration, boundSql, sql));
-		} else {
-			sqlBuilder.append(getSql(configuration, boundSql, boundSql.getSql()));
-		}
-		String statementId = mappedStatement.getId();
-		long start = SystemClock.now();
-		Object result = invocation.proceed();
-		long end = SystemClock.now();
-		long timing = end - start;
-		String sql = SqlUtils.sqlFormat(sqlBuilder.toString(), format);
-		System.err.println(" Time:" + timing + " ms" + " - ID:" + statementId + "\n Execute SQL:" + sql + "\n");
-		if (maxTime >= 1 && timing > maxTime) {
-			throw new MybatisPlusException(" The SQL execution time is too large, please optimize ! ");
-		}
-		return result;
-	}
-
-	public static String getSql(Configuration configuration, BoundSql boundSql, String sql) {
-		Object parameterObject = boundSql.getParameterObject();
-		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
-		sql = sql.replaceAll("[\\s]+", " ");
-		if (parameterMappings != null && parameterMappings.size() > 0 && parameterObject != null) {
-			TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
-			if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
-				sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
-			} else {
-				MetaObject metaObject = configuration.newMetaObject(parameterObject);
-				for (ParameterMapping parameterMapping : parameterMappings) {
-					String propertyName = parameterMapping.getProperty();
-					if (metaObject.hasGetter(propertyName)) {
-						Object obj = metaObject.getValue(propertyName);
-						sql = sql.replaceFirst("\\?", getParameterValue(obj));
-					} else if (boundSql.hasAdditionalParameter(propertyName)) {
-						Object obj = boundSql.getAdditionalParameter(propertyName);
-						sql = sql.replaceFirst("\\?", getParameterValue(obj));
-					}
-				}
-			}
-		}
-		return sql;
-	}
-
-	private static String getParameterValue(Object obj) {
-		String value;
-		if (obj instanceof String) {
-			value = obj != null ? "'" + obj.toString() + "'" : "''";
-		} else if (obj instanceof Date) {
-			if (obj instanceof java.sql.Date) {
-				value = obj != null ? "'" + obj.toString() + "'" : "''";
-			} else {
-				DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT,
-						Locale.CHINA);
-				value = obj != null ? "'" + formatter.format(obj) + "'" : "''";
-			}
-		} else {
-			value = obj != null ? obj.toString() : "";
-		}
-		return value;
-	}
-
-	public Object plugin(Object target) {
-		if (target instanceof Executor) {
-			return Plugin.wrap(target, this);
-		}
-		return target;
-	}
-
-	public void setProperties(Properties prop) {
-		// TODO
-	}
-
-	public long getMaxTime() {
-		return maxTime;
-	}
-
-	public void setMaxTime(long maxTime) {
-		this.maxTime = maxTime;
-	}
-
-	public boolean isFormat() {
-		return format;
-	}
-
-	public void setFormat(boolean format) {
-		this.format = format;
-	}
-
-	public String getOptimizeType() {
-		return optimizeType;
-	}
-
-	public void setOptimizeType(String optimizeType) {
-		this.optimizeType = optimizeType;
-	}
-}
+/**
+ * Copyright (c) 2011-2014, 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.plugins;
+
+import java.text.DateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+
+import org.apache.ibatis.executor.Executor;
+import org.apache.ibatis.mapping.BoundSql;
+import org.apache.ibatis.mapping.MappedStatement;
+import org.apache.ibatis.mapping.ParameterMapping;
+import org.apache.ibatis.plugin.Interceptor;
+import org.apache.ibatis.plugin.Intercepts;
+import org.apache.ibatis.plugin.Invocation;
+import org.apache.ibatis.plugin.Plugin;
+import org.apache.ibatis.plugin.Signature;
+import org.apache.ibatis.reflection.MetaObject;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.ResultHandler;
+import org.apache.ibatis.session.RowBounds;
+import org.apache.ibatis.type.TypeHandlerRegistry;
+
+import com.baomidou.mybatisplus.entity.CountOptimize;
+import com.baomidou.mybatisplus.entity.GlobalConfiguration;
+import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
+import com.baomidou.mybatisplus.plugins.pagination.DialectFactory;
+import com.baomidou.mybatisplus.plugins.pagination.Pagination;
+import com.baomidou.mybatisplus.toolkit.SqlUtils;
+import com.baomidou.mybatisplus.toolkit.StringUtils;
+import com.baomidou.mybatisplus.toolkit.SystemClock;
+
+/**
+ * <p>
+ * 性能分析拦截器,用于输出每条 SQL 语句及其执行时间
+ * </p>
+ * 
+ * @author hubin nieqiurong
+ * @Date 2016-07-07
+ */
+@Intercepts({
+		@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
+				RowBounds.class, ResultHandler.class }),
+		@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
+public class PerformanceInterceptor implements Interceptor {
+
+	/**
+	 * SQL 执行最大时长,超过自动停止运行,有助于发现问题。
+	 */
+	private long maxTime = 0;
+
+	private boolean format = false;
+	/**
+	 * count 优化方式
+	 */
+	private String optimizeType = "default";
+
+	public Object intercept(Invocation invocation) throws Throwable {
+		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
+		Object parameterObject = invocation.getArgs()[1];
+		RowBounds rowBounds = null;
+		Pagination pagination = null;
+		boolean isPageSql = false;
+		if (invocation.getMethod().getName().equals("query")) {
+			rowBounds = (RowBounds) invocation.getArgs()[2];
+			if (rowBounds instanceof Pagination) {
+				isPageSql = true;
+				Pagination page = (Pagination) rowBounds;
+				pagination = new Pagination(page.getCurrent(), page.getLimit());
+			}
+		}
+		BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
+		Configuration configuration = mappedStatement.getConfiguration();
+		StringBuilder sqlBuilder = new StringBuilder();
+		if (isPageSql) {
+			Pagination page = (Pagination) rowBounds;
+			boolean orderBy = true;
+			String dbType = GlobalConfiguration.getDbType(configuration).getDb();
+			if (page.isSearchCount()) {
+				CountOptimize countOptimize = SqlUtils.getCountOptimize(boundSql.getSql(), optimizeType, dbType,
+						page.isOptimizeCount());
+				orderBy = countOptimize.isOrderBy();
+			}
+			String sql = DialectFactory.buildPaginationSql(pagination,
+					SqlUtils.concatOrderBy(boundSql.getSql(), page, orderBy), dbType, null).replaceAll("[\\s]+", " ");
+			sqlBuilder.append(getSql(configuration, boundSql, sql));
+		} else {
+			sqlBuilder.append(getSql(configuration, boundSql, boundSql.getSql()));
+		}
+		String statementId = mappedStatement.getId();
+		long start = SystemClock.now();
+		Object result = invocation.proceed();
+		long end = SystemClock.now();
+		long timing = end - start;
+		String sql = SqlUtils.sqlFormat(sqlBuilder.toString(), format);
+		System.err.println(" Time:" + timing + " ms" + " - ID:" + statementId + "\n Execute SQL:" + sql + "\n");
+		if (maxTime >= 1 && timing > maxTime) {
+			throw new MybatisPlusException(" The SQL execution time is too large, please optimize ! ");
+		}
+		return result;
+	}
+
+	public static String getSql(Configuration configuration, BoundSql boundSql, String sql) {
+		Object parameterObject = boundSql.getParameterObject();
+		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
+		sql = sql.replaceAll("[\\s]+", " ");
+		if (parameterMappings != null && parameterMappings.size() > 0 && parameterObject != null) {
+			TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
+			if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
+				sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
+			} else {
+				MetaObject metaObject = configuration.newMetaObject(parameterObject);
+				for (ParameterMapping parameterMapping : parameterMappings) {
+					String propertyName = parameterMapping.getProperty();
+					if (metaObject.hasGetter(propertyName)) {
+						Object obj = metaObject.getValue(propertyName);
+						sql = sql.replaceFirst("\\?", getParameterValue(obj));
+					} else if (boundSql.hasAdditionalParameter(propertyName)) {
+						Object obj = boundSql.getAdditionalParameter(propertyName);
+						sql = sql.replaceFirst("\\?", getParameterValue(obj));
+					}
+				}
+			}
+		}
+		return sql;
+	}
+
+	private static String getParameterValue(Object obj) {
+		String value;
+		if (obj instanceof String) {
+			value = obj != null ? "'" + obj.toString() + "'" : "''";
+		} else if (obj instanceof Date) {
+			if (obj instanceof java.sql.Date) {
+				value = obj != null ? "'" + obj.toString() + "'" : "''";
+			} else {
+				DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT,
+						Locale.CHINA);
+				value = obj != null ? "'" + formatter.format(obj) + "'" : "''";
+			}
+		} else {
+			value = obj != null ? obj.toString() : "";
+		}
+		return value;
+	}
+
+	public Object plugin(Object target) {
+		if (target instanceof Executor) {
+			return Plugin.wrap(target, this);
+		}
+		return target;
+	}
+
+	public void setProperties(Properties prop) {
+		String maxTime = prop.getProperty("maxTime");
+		String format = prop.getProperty("format");
+		if (StringUtils.isNotEmpty(maxTime)) {
+			this.maxTime = Long.parseLong(maxTime);
+		}
+		if (StringUtils.isNotEmpty(format)) {
+			this.format = Boolean.valueOf(format);
+		}
+	}
+
+	public long getMaxTime() {
+		return maxTime;
+	}
+
+	public void setMaxTime(long maxTime) {
+		this.maxTime = maxTime;
+	}
+
+	public boolean isFormat() {
+		return format;
+	}
+
+	public void setFormat(boolean format) {
+		this.format = format;
+	}
+
+	public String getOptimizeType() {
+		return optimizeType;
+	}
+
+	public void setOptimizeType(String optimizeType) {
+		this.optimizeType = optimizeType;
+	}
+}

+ 14 - 1
mybatis-plus/src/main/java/com/baomidou/mybatisplus/service/IService.java

@@ -62,7 +62,7 @@ public interface IService<T> {
 	 * @param entityList
 	 *            实体对象列表
 	 * @param batchSize
-	 *
+	 *            插入批次数量
 	 * @return boolean
 	 */
 	boolean insertBatch(List<T> entityList, int batchSize);
@@ -170,6 +170,19 @@ public interface IService<T> {
 	 */
 	boolean updateBatchById(List<T> entityList);
 
+	/**
+	 * <p>
+	 * 根据ID 批量更新
+	 * </p>
+	 *
+	 * @param entityList
+	 *            实体对象列表
+	 * @param batchSize
+	 *            更新批次数量
+	 * @return boolean
+	 */
+	boolean updateBatchById(List<T> entityList, int batchSize);
+
 	/**
 	 * <p>
 	 * TableId 注解存在更新记录,否插入一条记录

+ 61 - 50
mybatis-plus/src/main/java/com/baomidou/mybatisplus/service/impl/ServiceImpl.java

@@ -15,15 +15,6 @@
  */
 package com.baomidou.mybatisplus.service.impl;
 
-import java.io.Serializable;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.ibatis.logging.Log;
-import org.apache.ibatis.logging.LogFactory;
-import org.apache.ibatis.session.SqlSession;
-import org.springframework.beans.factory.annotation.Autowired;
-
 import com.baomidou.mybatisplus.entity.TableInfo;
 import com.baomidou.mybatisplus.enums.SqlMethod;
 import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
@@ -37,6 +28,14 @@ import com.baomidou.mybatisplus.toolkit.MapUtils;
 import com.baomidou.mybatisplus.toolkit.ReflectionKit;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
+import org.apache.ibatis.logging.Log;
+import org.apache.ibatis.logging.LogFactory;
+import org.apache.ibatis.session.SqlSession;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
 
 /**
  * <p>
@@ -93,6 +92,46 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 		return SqlHelper.retBool(result);
 	}
 
+	public boolean insert(T entity) {
+		return retBool(baseMapper.insert(entity));
+	}
+
+	public boolean insertBatch(List<T> entityList) {
+		return insertBatch(entityList, 30);
+	}
+
+	/**
+	 * 批量插入
+	 *
+	 * @param entityList
+	 * @param batchSize
+	 * @return
+	 */
+	public boolean insertBatch(List<T> entityList, int batchSize) {
+		if (CollectionUtils.isEmpty(entityList)) {
+			throw new IllegalArgumentException("Error: entityList must not be empty");
+		}
+		SqlSession batchSqlSession = sqlSessionBatch();
+		try {
+			int size = entityList.size();
+			String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
+			for (int i = 0; i < size; i++) {
+				batchSqlSession.insert(sqlStatement, entityList.get(i));
+				if (i >= 1 && i % batchSize == 0) {
+					batchSqlSession.flushStatements();
+				}
+			}
+			batchSqlSession.flushStatements();
+		} catch (Exception e) {
+			logger.warn("Error: Cannot execute insertBatch Method. Cause:" + e);
+			return false;
+		} finally {
+			batchSqlSession.close();
+		}
+		return true;
+
+	}
+
 	/**
 	 * <p>
 	 * TableId 注解存在更新记录,否插入一条记录
@@ -127,14 +166,6 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 		return false;
 	}
 
-	public boolean insert(T entity) {
-		return retBool(baseMapper.insert(entity));
-	}
-
-	public boolean insertBatch(List<T> entityList) {
-		return insertBatch(entityList, 30);
-	}
-
 	public boolean insertOrUpdateBatch(List<T> entityList) {
 		return insertOrUpdateBatch(entityList, 30);
 	}
@@ -143,12 +174,12 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 		if (CollectionUtils.isEmpty(entityList)) {
 			throw new IllegalArgumentException("Error: entityList must not be empty");
 		}
+		SqlSession batchSqlSession = sqlSessionBatch();
 		try {
-			SqlSession batchSqlSession = sqlSessionBatch();
 			int size = entityList.size();
 			for (int i = 0; i < size; i++) {
 				insertOrUpdate(entityList.get(i));
-				if (i % batchSize == 0) {
+				if (i >= 1 && i % batchSize == 0) {
 					batchSqlSession.flushStatements();
 				}
 			}
@@ -156,39 +187,12 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 		} catch (Exception e) {
 			logger.warn("Error: Cannot execute insertOrUpdateBatch Method. Cause:" + e);
 			return false;
+		} finally {
+			batchSqlSession.close();
 		}
 		return true;
 	}
 
-	/**
-	 * 批量插入
-	 *
-	 * @param entityList
-	 * @param batchSize
-	 * @return
-	 */
-	public boolean insertBatch(List<T> entityList, int batchSize) {
-		if (CollectionUtils.isEmpty(entityList)) {
-			throw new IllegalArgumentException("Error: entityList must not be empty");
-		}
-		SqlSession batchSqlSession = sqlSessionBatch();
-		try {
-			int size = entityList.size();
-			for (int i = 0; i < size; i++) {
-				batchSqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entityList.get(i));
-				if (i % batchSize == 0) {
-					batchSqlSession.flushStatements();
-				}
-			}
-			batchSqlSession.flushStatements();
-		} catch (Exception e) {
-			logger.warn("Error: Cannot execute insertBatch Method. Cause:" + e);
-			return false;
-		}
-		return true;
-
-	}
-
 	public boolean deleteById(Serializable id) {
 		return retBool(baseMapper.deleteById(id));
 	}
@@ -217,15 +221,20 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 	}
 
 	public boolean updateBatchById(List<T> entityList) {
+		return updateBatchById(entityList, 30);
+	}
+
+	public boolean updateBatchById(List<T> entityList, int batchSize) {
 		if (CollectionUtils.isEmpty(entityList)) {
 			throw new IllegalArgumentException("Error: entityList must not be empty");
 		}
 		SqlSession batchSqlSession = sqlSessionBatch();
 		try {
 			int size = entityList.size();
+			String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
 			for (int i = 0; i < size; i++) {
-				batchSqlSession.update(sqlStatement(SqlMethod.UPDATE_BY_ID), entityList.get(i));
-				if (i % 30 == 0) {
+				batchSqlSession.update(sqlStatement, entityList.get(i));
+				if (i >= 1 && i % batchSize == 0) {
 					batchSqlSession.flushStatements();
 				}
 			}
@@ -233,6 +242,8 @@ public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
 		} catch (Exception e) {
 			logger.warn("Error: Cannot execute insertBatch Method. Cause:" + e);
 			return false;
+		} finally {
+			batchSqlSession.close();
 		}
 		return true;
 	}

+ 2 - 7
mybatis-plus/src/main/java/com/baomidou/mybatisplus/toolkit/ReflectionKit.java

@@ -58,13 +58,8 @@ public class ReflectionKit {
 	 */
 	public static String getMethodCapitalize(Field field, final String str) {
 		Class<?> fieldType = field.getType();
-		String concatstr;
-		if (Boolean.class.equals(fieldType) || boolean.class.equals(fieldType)) {
-			concatstr = "is";
-		} else {
-			concatstr = "get";
-		}
-		return StringUtils.concatCapitalize(concatstr, str);
+		// fix #176
+		return StringUtils.concatCapitalize(boolean.class.equals(fieldType) ? "is" : "get", str);
 	}
 
 	/**

+ 2 - 1
mybatis-plus/src/main/resources/template/entity.java.vm

@@ -6,8 +6,9 @@ import com.baomidou.mybatisplus.activerecord.Model;
 #foreach($pkg in ${table.importPackages})
 import ${pkg};
 #end
+#if(!${activeRecord} && !${superEntityClass})
 import java.io.Serializable;
-
+#end
 
 /**
  * <p>

+ 3 - 2
mybatis-plus/src/main/resources/template/mapper.xml.vm

@@ -4,8 +4,8 @@
 #if(${enableCache})
 	<!-- 开启二级缓存 -->
 	<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
-#end
 
+#end
 #if(${baseResultMap})
 	<!-- 通用查询映射结果 -->
 	<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
@@ -20,12 +20,13 @@
 #end
 #end
 	</resultMap>
-#end
 
+#end
 #if(${baseColumnList})
     <!-- 通用查询结果列 -->
     <sql id="Base_Column_List">
         ${table.fieldNames}
     </sql>
+
 #end
 </mapper>

+ 0 - 37
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MyFieldTypeConvert.java

@@ -1,37 +0,0 @@
-/**
- * Copyright (c) 2011-2016, 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.generator;
-
-import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
-import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
-
-/**
- * <p>
- * 测试字段类型转换
- * </p>
- *
- * @author hubin
- * @date 2017-01-20
- */
-public class MyFieldTypeConvert extends MySqlTypeConvert {
-
-	@Override
-	public DbColumnType processTypeConvert(String fieldType) {
-		System.out.println("转换类型:" + fieldType);
-		return super.processTypeConvert(fieldType);
-	}
-
-}

+ 15 - 6
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java

@@ -27,7 +27,9 @@ import com.baomidou.mybatisplus.generator.config.FileOutConfig;
 import com.baomidou.mybatisplus.generator.config.GlobalConfig;
 import com.baomidou.mybatisplus.generator.config.PackageConfig;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
+import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
@@ -51,7 +53,7 @@ public class MysqlGenerator {
 
 		// 全局配置
 		GlobalConfig gc = new GlobalConfig();
-		gc.setOutputDir("/home/nieqiurong/");
+		gc.setOutputDir("/develop/code/");
 		gc.setFileOverride(true);
 		gc.setActiveRecord(true);// 开启 activeRecord 模式
 		gc.setEnableCache(false);// XML 二级缓存
@@ -70,11 +72,18 @@ public class MysqlGenerator {
 		// 数据源配置
 		DataSourceConfig dsc = new DataSourceConfig();
 		dsc.setDbType(DbType.MYSQL);
-		dsc.setTypeConvert(new MyFieldTypeConvert());
+		dsc.setTypeConvert(new MySqlTypeConvert(){
+			// 自定义数据库表字段类型转换【可选】
+			@Override
+			public DbColumnType processTypeConvert(String fieldType) {
+				System.out.println("转换类型:" + fieldType);
+				return super.processTypeConvert(fieldType);
+			}
+		});
 		dsc.setDriverName("com.mysql.jdbc.Driver");
-		dsc.setUsername("nieqiurong");
-		dsc.setPassword("nieqiurong");
-		dsc.setUrl("jdbc:mysql://172.16.100.188:3306/mybatis-plus?characterEncoding=utf8");
+		dsc.setUsername("root");
+		dsc.setPassword("521");
+		dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");
 		mpg.setDataSource(dsc);
 
 		// 策略配置
@@ -128,7 +137,7 @@ public class MysqlGenerator {
 			@Override
 			public String outputFile(TableInfo tableInfo) {
 				// 自定义输入文件名称
-				return "D://my_" + tableInfo.getEntityName() + ".java";
+				return "/develop/code/my_" + tableInfo.getEntityName() + ".java";
 			}
 		});
 		cfg.setFileOutConfigList(focList);