MyBatis逆向工程基本操作及代码实例
回想一下MyBatis的基本操作,它需要实体类,自定义mapper接口以及mapper.xml配置文件。为了避免繁琐的工作量,MyBatis Generator,简称MBG,可自动生成框架所需的这些依赖,同时支持基本的CRUD操作,但是需要注意,MBG一般不要重复执行,否则会出问题。
下面是引入MBG的基本操作:
一、新建maven项目,引入依赖:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency></dependencies>
二、创建mbg配置文件:
<?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 targetRuntime='MyBatis3'> <!-- 连接池 --> <jdbcConnectiondriverClass='com.mysql.cj.jdbc.Driver'connectionURL='jdbc:mysql://localhost:3306/demo'userId='root'password='' ></jdbcConnection> <!-- 配置JavaBean生成策略 --> <javaModelGenerator targetPackage='com.wts.entity' targetProject='./src/main/java'></javaModelGenerator> <!-- 配置SQL映射文件生成策略 --> <sqlMapGenerator targetPackage='com.wts.entity' targetProject='./src/main/java'></sqlMapGenerator> <!-- 配置Mapper接口的生成策略 --> <javaClientGenerator targetPackage='com.wts.entity' targetProject='./src/main/java'></javaClientGenerator> <table tableName='user' domainObjectName='User'></table> </context></generatorConfiguration>
三、运行Generator:
public class MyTest { public static void main(String[] args) { List<String> warnings = new ArrayList<>(); File configFile = new File(MyTest.class.getResource('generatorConfig.xml').getFile()); ConfigurationParser configurationParser = new ConfigurationParser(warnings); Configuration configuration = null; try { configuration = configurationParser.parseConfiguration(configFile); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(true); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(configuration, callback, warnings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}
这都是固定写法,了解一下即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章: