写这个小博客是为了惊叹Mybatis逆向工程的技术
我之前一直都是自己写Entity以及Dao和Dao中接口的mapper文件,但是对于多表映射就显得工作量很大,很繁琐了,然后如果使用Mybatis的逆向工程,就是连接数据库,自动生成Entity实体类,Dao接口以及Dao接口的Mappper映射文件;
1.导入jar包到maven中
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
2.编写mng.xml(名字可以任意起)
<?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>
<context id="simple" targetRuntime="MyBatis3Simple">
//如果不加这句话的话,会生成很多注解,影响美观
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm"
userId="root"
password="123"/>
<!--指定Entity生成的位置-->
<javaModelGenerator targetPackage="Entity" targetProject="src/main/java"/>
<!--指定Dao接口生成的位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="Dao" targetProject="src/main/java"/>
<!--指定mapper文件的位置-->
<sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources"/>
<!--指定每个表的生成策略 -->
<table tableName="account" domainObjectName="Account" />
<table tableName="grade" domainObjectName="Grade" />
<table tableName="person" domainObjectName="Person" />
<table tableName="student" domainObjectName="Student" />
</context>
</generatorConfiguration>
3.运行(使用spring MVC自己的测试类进行测试:):
import org.junit.*;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class test {
@Test
public void text() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
4.结果:(因为我的项目是分层的,所以生成以后可自行粘贴,或者把mgn.xml中的targetPackage中的路径标注清楚)
5.展示我自己的例子
Entity.Account:
Dao.AccountMapper
Dao.AccountMapper.xml