idea中的mybatis生成方法
摘要
最近使用idea生成mybatis,发现坑真多,踩坑之后终于成功了,记录一下处理流程
1.配置文件
项目配置mybatis路径如下:
具体内容如下:
init.properties
###Mybatis Generator configuration
projectName=项目绝对路径(注意是绝对路径,相对路径,你会找不到你的配置文件)
driverJarPath=D:\\program\\repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar(这是你本地的mysql connector包的路径,需要更改)
jdbcDriverClass=com.mysql.jdbc.Driver
jdbcConnectionURL=jdbc:mysql://数据库ip:3306/数据库名称
jdbcUserId=账户
jdbcPassword=密码
javaModelTargetPackage=com.practice.demo.pojo 生成实体类文件路径
sqlMapTargetPackage=com.practice.demo.mapper 生成mapper路径
javaClientTargetPackage=com.practice.demo.dao 生成dao接口i路径
generatorConfig.properties
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="generator/init.properties" />
<classPathEntry location="${driverJarPath}" />
<!-- targetRuntime代码生成目标,默认是MyBatis3,可以是Ibatis2Java2或者Ibatis2Java5 -->
<context id="MYSQLTables" targetRuntime="MyBatis3">
<!-- Pagination -->
<!-- 分页实体类路径 此处需要更改为你项目中配置的分页类 -->
<plugin type="com.practice.demo.PaginationPlugin"/>
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库连接 对应init配置中的路径 -->
<jdbcConnection driverClass="${jdbcDriverClass}"
connectionURL="${jdbcConnectionURL}" userId="${jdbcUserId}" password="${jdbcPassword}" />
<!-- 解决数字转换问题 -->
<javaTypeResolver>
<!-- 只有一个属于forceBigDecimals,默认false。如果字段精确超过0,生成BigDecimal 如果字段精确是0,总长度10-18生成Long;
如果字段精确是0,总长5-9生成Integer; 如果字段精确是0,总长小于5生成Short; 如果forceBigDecimals为true,统一生成BigDecimal -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="${javaModelTargetPackage}"
targetProject="${projectName}">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="${sqlMapTargetPackage}"
targetProject="${projectName}">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="${javaClientTargetPackage}" targetProject="${projectName}">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- tableName表名称,此处使用ug_mobile_log替代,domainObjectName代表你生成实体类时候的名称,一般驼峰命名即可,column 主键 -->
<table tableName="ug_mobile_log" domainObjectName="UgMobileLog">
<generatedKey column="id" sqlStatement="MySql" identity="true" />
</table>
</context>
</generatorConfiguration>
分页类
/**
* <P>File name : PaginationPlugin.java </P>
* <P>Author : fly </P>
* <P>Date : 2013-7-2 上午11:50:45 </P>
*/
public class PaginationPlugin extends PluginAdapter {
@Override
public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
// add field, getter, setter for limit clause
addLimit(topLevelClass, introspectedTable, "limitStart");
addLimit(topLevelClass, introspectedTable, "limitEnd");
return super.modelExampleClassGenerated(topLevelClass,
introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(
XmlElement element, IntrospectedTable introspectedTable) {
// XmlElement isParameterPresenteElemen = (XmlElement) element
// .getElements().get(element.getElements().size() - 1);
XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$
isNotNullElement.addAttribute(new Attribute("test", "limitStart != null and limitStart>=0")); //$NON-NLS-1$ //$NON-NLS-2$
// isNotNullElement.addAttribute(new Attribute("compareValue", "0")); //$NON-NLS-1$ //$NON-NLS-2$
isNotNullElement.addElement(new TextElement(
"limit #{limitStart} , #{limitEnd}"));
// isParameterPresenteElemen.addElement(isNotNullElement);
element.addElement(isNotNullElement);
return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,
introspectedTable);
}
private void addLimit(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable, String name) {
CommentGenerator commentGenerator = context.getCommentGenerator();
Field field = new Field();
field.setVisibility(JavaVisibility.PROTECTED);
// field.setType(FullyQualifiedJavaType.getIntInstance());
field.setType(PrimitiveTypeWrapper.getIntegerInstance());
field.setName(name);
// field.setInitializationString("-1");
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setName("set" + camel);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
method.addBodyLine("this." + name + "=" + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
method = new Method();
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(PrimitiveTypeWrapper.getIntegerInstance());
method.setName("get" + camel);
method.addBodyLine("return " + name + ";");
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
}
/**
* This plugin is always valid - no properties are required
*/
public boolean validate(List<String> warnings) {
return true;
}
}
pom文件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 你分页实体类所在的项目 导入-->
<dependency>
<groupId>com.practice.common</groupId>
<artifactId>项目名称</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>
</plugin>
这部分如果你的项目是微服务,这个就是必须的,因为,你不导入分页类所在的项目,会出现类型无法转换的错误,说白了就是没有找到对应的实体类;
运行生成
经此准备之后,你只需要将项目打到你本地,之后,找到
点击运行,即可生成mapper
追加
注意,如果数据库服务器中有多张同名的表,则存在一个问题,就是,生成的mapper文件也会生成多个,会造成服务的报错,这个时候需要修改generatorConfig.properties配置,修改如下
<!-- 数据库连接 -->
<jdbcConnection driverClass="${jdbcDriverClass}"
connectionURL="${jdbcConnectionURL}" userId="${jdbcUserId}" password="${jdbcPassword}" >
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>