1.首先要有一个generatorConfig.xml.
2.在这个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>
<!-- 数据库驱动 ,这个数据库驱动的地址是我自己在网上下载的jar,放到本地,然后手动引入-->
<classPathEntry location="D:\mysqljar\mysql-connector-java-5.0.8-bin\mysql-connector-java-5.0.8-bin.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true" />
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root" password="">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.cn.model"
targetProject="src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置 -->
<sqlMapGenerator targetPackage="com.cn.mapping"
targetProject="src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.cn.mapper"
targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 ,
下面的true和false的作用是,是否生成example类,根据example条件查询这个实体,个人建议生成
这样单表的错做会非常简单。-->
<table tableName="user" domainObjectName="User"
enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true"
selectByExampleQueryId="true" >
</table>
</context>
</generatorConfiguration>
3.注意生成路径地址一定要和你项目的结构一样(当然不一样也能生成出,但是你得手动修改包路径)。
4.当项目都生成完成以后,该生成相应的文件了。
public static void main(String[] args) {
List<String> warnings = new ArrayList<String>();
try {
String configFilePath = System.getProperty("user.dir").concat("/src/main/resources/generatorConfig.xml");
System.out.println("加载配置文件===" + configFilePath);
boolean overwrite = true;
File configFile = new File(configFilePath);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
ProgressCallback progressCallback = new VerboseProgressCallback();
// myBatisGenerator.generate(null);
myBatisGenerator.generate(progressCallback);
}
catch (Exception e) {
e.printStackTrace();
}
for (String warning : warnings) {
System.out.println(warning);
}
}
启动此main方法,就可以生成出来了。
本文介绍如何使用MyBatis Generator工具自动生成数据库操作相关的Java代码,包括实体类、映射文件及DAO接口等,简化开发流程。
488

被折叠的 条评论
为什么被折叠?



