1.概述
MyBatis的逆向工程是:Mybatis Generator:
它是一个专门为Mybatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询
2. 使用
项目结构如下:
- 导入依赖
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
- 创建配置文件mbg.xml
从官方文档中复制
<!--MyBatis3Simple:生成简单版的CRUD
MyBatis:生成复杂版
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!--jdbcConnection:指定如何连接到目标数据库-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="123456">
</jdbcConnection>
<!--javaTypeResolver:java类型的解析器-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--javaModelGenerator:指定javaBean的生成策略
targetPackage:目标包名
targetProject:目标工程
-->
<javaModelGenerator targetPackage="com.ls.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--sqlMapGenerator:sql映射生成策略-->
<sqlMapGenerator targetPackage="mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--javaClientGenerator:指定mapper接口所在的位置-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ls.dao"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--table:逆向分析哪些表,根据表创建javaBean-->
<table tableName="tbl_employee" domainObjectName="Employee">
</table>
<table tableName="tbl_dept" domainObjectName="Department">
</table>
</context>
- 执行RunMbg()方法,就可以自动生成代码以及配置文件了
public class MybatisTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void RunMbg() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//mbg.xml配置文件
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);
}
}
3.结束!!