二:mybatis逆向生成接口和映射
2020-04-11 本文已影响0人
煎包小混沌
1:添加项目依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--mybatis逆向生成插件-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
2:mybatis-generator 配置文件,指定生成类和映射文件的路径及名称
image.png<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!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="sql/jdbc.properties"></properties>
<!--指定特定数据库的jdbc驱动jar包的位置-->
<classPathEntry location="${jdbc.driverLocation}"/>
<context id="default" targetRuntime="MyBatis3">
<!-- JavaBean 实现 序列化 接口 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- genenat entity时,生成toString -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- optional,旨在创建class时,对注释进行控制 -->
<!--1:配置文件路径-->
<commentGenerator type="mybatis.config.CommentGenerator">
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection
driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<!--2:对应数据库生成的实体类路径-->
<javaModelGenerator targetPackage="mybatis.entity"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="false"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
<!--2.1:指定生成的实体继承此实体类-->
<!--<property name="rootClass" value="com.building.cloudclientuser.base.MybatisBaseModel"/>-->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<!--3:对应接口生成的xml文件路径-->
<sqlMapGenerator targetPackage="myBatisMapper"
targetProject="src/main/resources/">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<!--4:对应生成的数据库操作接口类文件路径-->
<javaClientGenerator targetPackage="mybatis.dao"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
<!--4.1:指定生成的接口继承此接口-->
<!--<property name="rootInterface" value="com.building.cloudclientuser.base.MybatisBaseDao"/>-->
</javaClientGenerator>
<!--指定User会查询到mysql默认数据库中的user表,设置 catalog 指定数据库-->
<table tableName="student" mapperName="StudentDao" catalog="mybatis" delimitIdentifiers="true"
domainObjectName="StudentModel" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
<property name="ignoreQualifiersAtRuntime" value="true"/>
<!-- 下面子属性是保持数据库与实体类字段名一致性 -->
<property name="useActualColumnNames" value="true"/>
</table>
</context>
</generatorConfiguration>
#mysql驱动的路径
jdbc.driverLocation=/Users/apple/Tomcat/apache-tomcat-9.0.14/webapps/ROOT/WEB-INF/lib/mysql-connector-java-5.1.6.jar
jdbc.driverClass=com.mysql.cj.jdbc.Driver
#根据自己的地址修改
jdbc.connectionURL=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false&useServerPrepStmts=true&cachePrepStmts=true
jdbc.userId=root
jdbc.password=********
3:CommentGenerator,用来读取sql数据库的属性等
package mybatis.config;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.api.dom.java.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
// 注释生成 会获取到mysql数据库字段注释
public class CommentGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;
public CommentGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
field.addJavaDocLine(sb.toString().replace("\n", " "));
field.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
}
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
}
4:创建启动类MyBatisGeneratorRun
package mybatis.config;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
// 自动生成插件启动类
public class MyBatisGeneratorRun {
public static void main(String[] args) throws Exception{
MyBatisGeneratorRun app = new MyBatisGeneratorRun();
System.out.println(app.getClass().getResource("/").getPath());
app.generator();
System.out.println(System.getProperty("user.dir"));
}
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("myBatis/generator.config.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(resourceAsStream);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for(String warning:warnings){
System.out.println(warning);
}
}
}