1.概述:
4.运行程序
mybatis需要程序员自己编写的SQL。
mybatis官方提供了逆向工程,可以针对单表自动生成mybatis执行所需要的代码
(mapper,java,maper.xml,po...)
一般都是由数据库到java代码, 的生成过程
2.导入jar包:
mybatis-3.1.1.jar
mybatis-generator.core-1.3.2.jar
mysql-connxction-java-5.1.28-bin.jar
3.新建generatorConfig.xml 配置xml
<span style="font-size:12px;"><?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="testTables" targetRuntime="MyBatis3">
<!-- 数据库连接信息 驱动类 连接地址 用户名 密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/managercar?character=utf8"
userId="root"
password="root">
</jdbcConnection>
<!--默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成po类的位置 -->
<javaModelGenerator targetPackage="com.ketech.carmanager.po" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- mapper映射文件的生成位置 -->
<sqlMapGenerator targetPackage="com.ketech.carmanager.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ketech.carmanager.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="tb_brand"></table>
<table tableName="tb_brand_backup"></table>
</context>
</generatorConfiguration> </span>
4.运行程序
java程序
<span style="font-size:12px;">import java.io.File;
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.internal.DefaultShellCallback;
public class GeneratorSqlMap {
public static void main(String[] args) {
GeneratorSqlMap generatorSqlMap = new GeneratorSqlMap();
try {
generatorSqlMap.genetator();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void genetator()throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.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);
}
}</span><span style="font-size: 18px;">
</span>
运行main函数,就可生成mapper和po包