mybatis官方提供逆向工程 可以针对单表自动生成mybatis执行所需要的代码(JavaBean,Xxxmapper.java,XxxMapper.xml)
导入mybatis-generator-core-xxx.jar文件,在项目路径下编写mbg.xml配置文件。
mbg.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="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/name" userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javabean的生成位置 -->
<javaModelGenerator targetPackage="club.hl.bean"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定sql映射文件的生成位置 -->
<sqlMapGenerator targetPackage="club.hl.mapper"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定到接口的生成位置,mapper接口生成位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="club.hl.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- table指定每个表的生成策略 -->
<table tableName="tabletest1" domainObjectName="People"></table>
<table tableName="tabletest2" domainObjectName="Order"></table>
</context>
</generatorConfiguration>
运行以下程序:加载配置文件,指定生成文件:
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
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;
public class MBGTest {
public static void main(String[] args) 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);
}
}
运行后,刷新项目即可看到如下结果:
这样就可以节省了程序员不少的开发时间,程序员只需要在上面的基础上进行相应的增加和修改即可。(ps:建议一开始学习,还是手写的好,熟悉流程)
注:以上文章仅是个人学习过程总结,若有不当之处,望不吝赐教。