这篇文章将要介绍的是MyBatis Generator(也就是MyBatis代码生成)
想要查看MyBatis使用教程、MyBatis批量新增、MyBatis的in条件查询(foreach使用),MyBatis二级缓存、MyBatis工作原理、MyBatis插件使用在另外一篇文章中。点击查看
一、介绍
MyBatis Generator (简称MBG)有的资料又称为MyBatis逆向工程;它是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查的生成,以及QBC风格的条件查询的生成,但是表连接、存储过程等这些复杂sql的定义需要我们手工编写。
这个项目也是可以在 github 上的 MyBatis 开源项目上找到。(也就是进入https://github.com/mybatis就能找到,也就是在Mybatis 开源项目网站里面的 generator)
官方文档地址 http://www.mybatis.org/generator/
官方工程地址 https://github.com/mybatis/generator/releases (就是在Mybatis开源项目官网下的generator)
二、操作示例
-
引入依赖: 数据库驱动 mybatis-generator-core就可以了。想测试生成后的效果就引入mybatis
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xxx.mybatisdemo</groupId> <artifactId>mybatis-demo13-mbg</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatis-demo13-mbg</name> <packaging>jar</packaging> <description>mybatis入门</description> <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> <scope>runtime</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <!-- 为了方便查看Mybatis的日志,这里引入一下log4j。 还要引入一个log4j.xml的文件 不引入没有日志查看 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
-
编写mbg的文件。(名字怎么起无所谓) 这里把这个文件放在了类路径下
- 编写MBG的配置文件(重要几处配置) 也可以进入官方文档查看Quick Start Guide 来教你怎么用;
<jdbcConnection>
配置数据库连接信息<javaModelGenerator>
配置javaBean的生成策略<sqlMapGenerator>
配置sql映射文件生成策略<javaClientGenerator>
配置Mapper接口的生成策略<table>
配置要要生成代码的数据表- 更多的节点配置信息可以查看官方文档 XML Configuration 菜单
<?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> <!-- targetRuntime="MyBatis3Simple":生成简单版的CRUD targetRuntime="MyBatis3":生成豪华版 (带条件拼接的代码,和支持QBC方式查询的代码) --> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- jdbcConnection:指定如何连接到目标数据库 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true" userId="root" password="root"> </jdbcConnection> <!-- 这里的配置是说是否强制转换Decimals 数值的那些个。可以查看官方文档有详细的介绍 --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- javaModelGenerator:指定javaBean的生成策略 targetPackage="test.model":目标包名 targetProject="\MBGTestProject\src":目标工程 --> <javaModelGenerator targetPackage="com.xxx.mybatis.entity" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- sqlMapGenerator:sql映射生成策略: --> <sqlMapGenerator targetPackage="mybatis.mapper" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- javaClientGenerator:指定mapper接口所在的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mybatis.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定要逆向分析哪些表:根据表要创建javaBean --> <!-- <table tableName="tbl_dept" domainObjectName="Department"></table> --> <table tableName="employee" domainObjectName="Employee"></table> </context> </generatorConfiguration>
- 编写MBG的配置文件(重要几处配置) 也可以进入官方文档查看Quick Start Guide 来教你怎么用;
-
编写代码,然后运行代码让他生成代码。
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 MainTest { public static void main(String[] args) throws Exception { testMyBatisGenerator(); } private static void testMyBatisGenerator() throws Exception { // 这个代码官网里也有 List<String> warnings = new ArrayList<String>(); boolean overwrite = true; // 将配置文件的路径编写正确,这里只是示例 File configFile = new File("mbg.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); } }
注意:
-
Context标签的
targetRuntime="MyBatis3"
可以生成带条件的增删改查,会生成(带条件拼接的代码,和支持QBC方式查询的代码) -
Context标签的
targetRuntime ="MyBatis3Simple"
可以生成基本的增删改查 (生成简单版的增、删、改、查) -
如果再次生成,建议将之前生成的数据删除,避免xml向后追加内容出现的问题
-
想要用类似Hibernate QBC的查询,需要在 mbg生成代码时用
<context id="xxx" targetRuntime="MyBatis3">
targetRuntime="MyBatis3"的方式生成。用targetRuntime="MyBatis3"生成的代码,会有带条件拼接sql的代码,同时也多了xxxExample的类; xxxExample类就是封装查询条件的;他就是用来我们做复杂条件查询封装复杂条件的。import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.xxx.mybatis.entity.Employee; import com.xxx.mybatis.entity.EmployeeExample; import com.xxx.mybatis.entity.EmployeeExample.Criteria; import com.xxx.mybatis.mapper.EmployeeMapper; public class MainTest { public static void main(String[] args) throws Exception { testQBCquery(); } /** * 想要用类似Hibernate QBC的查询,需要在 mbg生成代码时用 <context id="xxx" targetRuntime="MyBatis3"> targetRuntime="MyBatis3"的方式生成 * * 用targetRuntime="MyBatis3"生成的代码,会有带条件拼接sql的代码,同时也多了xxxExample的类; xxxExample类就是封装查询条件的;他就是用来我们做复杂条件查询封装复杂条件的 * * @throws Exception */ public static void testQBCquery() throws Exception{ //1、根据xml文件(全局配置文件)来创建一个SqlSessionFactory 多层包,在这里用斜杠表示,有的地方用点表示,需要注意。 String resource = "mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2、通过 SqlSessionFactory 获取 SqlSession来执行 mapper.xml (映射文件) 中的sql语句 SqlSession sqlSession = sqlSessionFactory.openSession(); try{ //3、通过sqlSession.getMapper(接口的class) 获取接口的实现对象 (mybatis会为接口自动创建一个代理对象,代理对象去执行增删改查方法) EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //测试1:查询所有 (简单查询) //List<Employee> emps = mapper.selectByExample(null); 想查询全部,不带条件,就可传一个null //测试2:查询员工名字中有e字母的,和员工性别是1的 //封装员工查询条件的example xxxExample就是封装查询条件的 EmployeeExample example = new EmployeeExample(); //创建一个Criteria,这个Criteria就是拼装查询条件 //select id, last_name, email, gender, d_id from temployee WHERE ( last_name like ? and gender = ? ) or email like "%e%" Criteria criteria = example.createCriteria(); criteria.andLastNameLike("%e%"); criteria.andGenderEqualTo("1"); Criteria criteria2 = example.createCriteria(); criteria2.andEmailLike("%e%"); example.or(criteria2); List<Employee> list = mapper.selectByExample(example); //想查询全部,不带条件,就可传一个null for (Employee employee : list) { System.out.println(employee.getId()); } }finally{ sqlSession.close(); } } }
-