Mybatis-generator生成VO属性Long转换为String

一、场景

		数据库表中属性为BigInt类型的字段生成对应VO时,VO中对应的属性转换为String

二、版本

		<parent>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-parent</artifactId>
			<version>1.5.9.RELEASE</version>
		</parent>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		 <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.4</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>1.1.0</version>
		</dependency>

三、项目中使用了TK生成代码插件,所以自定义插件要继承TK插件类

1、自定义插件类

package com.seentao.test;
import java.util.List;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import tk.mybatis.mapper.generator.MapperPlugin;

/**
 **VO中对应数据库BigInt类型的属性,生成时转换为String
 * @author wy
 * @date 2019年11月23日
 */
public class MybatisGeneratorPlugin extends MapperPlugin {

	    /**
	     *	 改变属性类型Long为String
	     */
	    @Override
	    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
	    	List<Field> fields = topLevelClass.getFields();
	    	for (Field field : fields) {
	    		if(field.getType().compareTo(new FullyQualifiedJavaType("java.lang.Long"))==0) {
	    			field.setType(new FullyQualifiedJavaType("java.lang.String"));
	    		}
			}
	    	return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
	    }
	    
	    /**
         *    设置get set 方法返回值参数类型
	     * 
	     */
	    @Override
	    public boolean modelGetterMethodGenerated(Method method,
	            TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
	            IntrospectedTable introspectedTable,
	            Plugin.ModelClassType modelClassType) {
	    	if(introspectedColumn.getFullyQualifiedJavaType().compareTo(
	    			new FullyQualifiedJavaType("java.lang.Long"))==0) {
	    		method.setReturnType(new FullyQualifiedJavaType("java.lang.String"));
	    		introspectedColumn.setFullyQualifiedJavaType(new FullyQualifiedJavaType("java.lang.String"));
	    	}
	        return true;
	    }
	    
	   
}

2、配置文件中配置插件

<plugin type="xxx.xxx.xxx.MybatisGeneratorPlugin">
     <property name="mappers" value="com.seentao.base.mybatis.BasicMapper"/>
 </plugin>
发布了17 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/xiangwangye66/article/details/103233442
今日推荐