1. 程式人生 > >13.mybatis_generator(傳智播客)

13.mybatis_generator(傳智播客)

需求:根據資料庫的表資訊自動生成po類、mapeper介面以及sql對映檔案

一.配置檔案

<?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">
	        <!-- 1.配置資料來源 -->
	        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
	                        connectionURL="jdbc:mysql://localhost:3306/mybatis?useSSL=false"
	                        userId="root"
	                        password="admin123">
	        </jdbcConnection>
	
	        <javaTypeResolver >
	            <property name="forceBigDecimals" value="false" />
	        </javaTypeResolver>
	
	        <!-- 2.生成po類的位置 -->
	        <javaModelGenerator targetPackage="po" targetProject="src/main/java">
	            <property name="enableSubPackages" value="true" />
	            <property name="trimStrings" value="true" />
	        </javaModelGenerator>
	
	        <!-- 3.生成mapper介面和sql對映檔案的的位置 -->
	        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
	            <property name="enableSubPackages" value="true" />
	        </sqlMapGenerator>
	
	        <javaClientGenerator type="XMLMAPPER" targetPackage="mapper"  targetProject="src/main/java">
	            <property name="enableSubPackages" value="true" />
	        </javaClientGenerator>
	
	        <!-- 4.配置要生成的資料庫表資訊 -->
	        <table tableName="item"/>
	        <table tableName="user"/>
	    </context>
	</generatorConfiguration>

在generatorConfig.xml中配置mapper生成的詳細資訊,注意修改以下幾點配置:
1.新增要生成的資料表名稱
2.生成po類的位置
3.生成mapper介面和sql對映檔案的的位置

二.使用java類生成mapper介面、sql對映檔案以及po類檔案

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("E:\\Codes\\demo\\mybatis_generator\\src\\main\\resources\\config\\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);
}