MyBatis Generator(MBG)
【目录】
1 什么是MyBatis Generator(MBG)
2 搭建MBG项目
4 使用自动生成的文件操作数据库
1 什么是MyBatis Generator(MBG)
简单来说,MyBatis Generator是一个Mybatis和ibatis的代码生成器,它可以根据数据库表自动生成Bean对象、Java接口及SqlMapper.xml配置文件。
2 搭建MBG项目
在项目开始之前准备好数据库。
数据库database:
![](https://img.haomeiwen.com/i12413187/ce6167c58810b6bf.png)
![](https://img.haomeiwen.com/i12413187/5a9b2b27068f28eb.png)
![](https://img.haomeiwen.com/i12413187/25751dbfe0547d48.png)
![](https://img.haomeiwen.com/i12413187/20c1a92405bd2034.png)
下面开始正式的搭建。
1.下载MBG核心包。
下载地址。
- 创建java项目。
![](https://img.haomeiwen.com/i12413187/37f934cd219f9264.png)
3.导入依赖包。
![](https://img.haomeiwen.com/i12413187/e98bba04ee0cd545.png)
4.从官方文档获取配置表、实例代码。
创建src/generatorConfig.xml。
把官方文档MyBatis GeneratorXML Configuration File Reference的配置复制到generatorConfig.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>
<!-- 配置数据库连接的包 -->
<!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> -->
<!-- context指定环境 -->
<context id="MyGererator" targetRuntime="MyBatis3">
<!-- 这个标签可以去掉MBG各类元素生成的注释,默认是全部生成的 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/database?useSSL=false"
userId="root"
password="admin">
</jdbcConnection>
<!-- JAVA JDBC数据类型转换,参照官方文档,不再细说 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator javaBean配置
targetPackage 输入包名 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.test.bean" targetProject="src">
<!-- enableSubPackages 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set方法中加入.trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 映射文件mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.test.mapper" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 动态代理类接口,和mapper.xml在要同一个路径 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.test.mapper" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 数据表 根据数据库中的表来生成 -->
<table tableName="user"/>
<table tableName="country"/>
<!-- 数据表更详细的属性参见官方文档,这里注释掉,不细讲 -->
<!-- <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table> -->
</context>
</generatorConfiguration>
这里推荐一篇博文——Mybatis Generator最完整配置详解。
新建com.test包,包内新建Generator.java。
把官方文档Running MBG from Java with an XML Configuration File的配置复制到Generator.java中,加以修改,代码如下:
package com.test;
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 Generator {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/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);
}
}
5.右键Generator.java运行,生成所需文件(Bean、Interface、Mapper.xml)。
刷新目录即可看到生成的文件。
![](https://img.haomeiwen.com/i12413187/40afd6803b531413.png)
3 使用自动生成的文件操作数据库
复制上面的项目HelloMyBatis_Generator,命名为HelloMyBatis_Generator1。
在User.java里添加toString方法,方便测试。
@Override
public String toString() {
return "User [uId=" + uId + ", uUsername=" + uUsername + ", uPassword=" + uPassword + ", uSex=" + uSex
+ ", uCreatetime=" + uCreatetime + ", uCid=" + uCid + "]";
}
新建主配置文件sqlMapConfig.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<!-- 使用jdbc的事务 -->
<transactionManager type="JDBC"/>
<!-- 使用连接池 连接数据库 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/database?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射器的位置 -->
<mappers>
<package name="com.test.mapper"/>
</mappers>
</configuration>
新建com.test.test包,包内新建MapperTest.java。代码如下:
package com.test.test;
import java.io.IOException;
import java.io.InputStream;
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 org.junit.Test;
import com.test.bean.User;
import com.test.bean.UserExample;
import com.test.mapper.UserMapper;
public class MapperTest {
@Test
public void Test1() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
//按主键查询
User user = mapper.selectByPrimaryKey(1);
System.out.println("按主键查询");
System.out.println(user);
}
@Test
public void Test2() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
UserExample example = new UserExample();
//将条件封装到createCriteria集合中 -条件列表
example.createCriteria().andUSexEqualTo("男").andUUsernameLike("%老%");
//按条件查询
List<User> list = mapper.selectByExample(example);
System.out.println("按条件查询");
for (User user : list) {
System.out.println(user);
}
}
@Test
public void Test3() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource );
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
SqlSession session = ssf.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User() ;
//数据库表中这四个字段设置为不为空,但id可以自增所以不用填写数据,剩下三个不能自增的必须填写
//user.setuId(123);
user.setuUsername("哈哈");
user.setuPassword("133");
user.setuCid(12);
mapper.insertSelective(user);
session.commit();
System.out.println("插入成功");
}
}
进行测试。
![](https://img.haomeiwen.com/i12413187/bcc8f36db055d901.png)
小tips:
1.如果运行提示错误如下:
Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for xyx.dsw.dao.mapper.admin.quotationwish.TempTestTableMapper.TempTestTableResult
可以尝试删掉生成的文件,重新生成代码。一般是因为MBG生成了两次代码,出现了映射错误。
2.插入一条新数据时,数据库表中设置为不为空的字段,必须填写(可以自增的除外)。