- 原本实体类、Mapper文件、接口文件都需要程序员编写,但是用逆向工程可以让Mybatis根据数据表来创建出实体类、Mapper文件、接口文件,同时Mybatis还会生成高级的SQL语句供程序员使用。其实就是一个代码生成器。
(1)创建mybatis-generator.xml配置文件
<!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">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123456"/>
<javaModelGenerator
targetPackage="com.wsh.pojo"
targetProject="src/main/java"/>
<sqlMapGenerator
targetPackage="mapper"
targetProject="src/main/resources"/>
<javaClientGenerator
type="ANNOTATEDMAPPER"
targetPackage="com.wsh.mapper"
targetProject="src/main/java"/>
<table tableName="employee" domainObjectName="Employee"/>
<table tableName="department" domainObjectName="Department"/>
</context>
</generatorConfiguration>
(2)JAVA程序
public void test() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("D:\\码码码\\javaCode\\Mybatis01\\src\\main\\resources\\mybatis-generator.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);
}
|