Java根据数据表生成xml_MyBatis逆向工程——根据数据表自动生成model、xml映射文件、mapper接口...

本文介绍了如何使用MyBatis Generator(MBG)根据数据表生成Java模型、XML映射文件和Mapper接口。通过下载MBG的jar包,配置config.xml文件,设置数据库连接信息和生成文件的位置,然后运行主类生成代码。虽然MBG能快速生成基础代码,但复杂的关联查询仍需手动编写。推荐官方文档和带GUI的代码生成器辅助操作。
摘要由CSDN通过智能技术生成

spring+spring mvc mybatis整合

113.5元

包邮

(需用券)

去购买 >

7c3c2fdaa721f1f38e1e8503f447af8f.png

MyBatis Generator(MBG)的使用

MBG可以根据数据表生成对应的model、xml映射文件、mapper接口,只是简单的生成,还需要根据需求修改。

1、下载jar包

https://github.com/mybatis/generator/releases

1f6a388ff06bf35e821cc0be69e7ff02.png

解压后有3个jar包,只使用一个:

2ec758ec582bd416ec79246997b2059b.png

2、新建一个新的java项目,导入mybatis.jar、mybatis-generator-core.jar、数据库驱动。

3、src下新建config.xml

http://mybatis.org/generator/configreference/xmlconfig.html

到官网复制xml文档,修改如下:

/p>

PUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

红字部分是需要修改的。主要是修改数据库的连接信息、文件的生成位置。

xml文件的详细配置可参考官方文档:http://mybatis.org/generator/configreference/xmlconfig.html

4、src下新建主类test.Test

http://mybatis.org/generator/running/runningWithJava.html

到官网复制代码来改, 注意是xml那个,修改如下:

packagetest;importorg.mybatis.generator.api.MyBatisGenerator;importorg.mybatis.generator.config.Configuration;importorg.mybatis.generator.config.xml.ConfigurationParser;importorg.mybatis.generator.exception.InvalidConfigurationException;importorg.mybatis.generator.exception.XMLParserException;importorg.mybatis.generator.internal.DefaultShellCallback;importjava.io.File;importjava.io.IOException;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;public classTest {public static void main(String[] args) throwsIOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {

List warnings = new ArrayList();boolean overwrite = true;

File configFile= new File("src/config.xml");

ConfigurationParser cp= newConfigurationParser(warnings);

Configuration config=cp.parseConfiguration(configFile);

DefaultShellCallback callback= newDefaultShellCallback(overwrite);

MyBatisGenerator myBatisGenerator= newMyBatisGenerator(config, callback, warnings);

myBatisGenerator.generate(null);

}

}

只需注意xml文件的路径是否正确。

5、运行主类,将生成的文件复制到要使用的项目中,根据需要修改。

只能生成简单的代码,复杂的还需要自己写,比如关联查询。

文件名可随意取,只要xml文件路径对得上即可。常用generatorConfig.xml、Generator.java,觉得难写可以使用简单的单词代替。

官网:http://mybatis.org/generator/index.html

github:https://github.com/mybatis/generator

带GUI的代码生成器:https://github.com/zouzg/mybatis-generator-gui

原文链接:https://www.cnblogs.com/chy18883701161/p/12227853.html

java 11官方入门(第8版)教材

79.84元

包邮

(需用券)

去购买 >

f0f3f55624fb396b1764d42d6df88864.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值