官方文档  传送门

    下载地址  传送门

MyBatis Generator(MBG)简介:

  MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器。它将为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码。它将内省数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的初始麻烦。MBG寻求对简单CRUD(创建,检索,更新,删除)的大部分数据库操作产生重大影响。您仍然需要为连接查询或存储过程手动编写SQL和对象代码。

  

创建一个简单的MyBatis Generator项目

  1、搭建MBG项目;
    a)下载MBG核心包;
    b)创建java项目;
    c)从官方文档获取配置表、实例代码;
    d)导入依赖包;
  2、MBG配置以及根据数据库表生成所需文件(Bean、Interface、Mapper.xml);
  3、使用自动生成的文件操作数据库;

  准备数据库

  JavaWeb_(Mybatis框架)MyBatis Generator简单入门-LMLPHP

  JavaWeb_(Mybatis框架)MyBatis Generator简单入门-LMLPHP

/*
SQLyog Professional v12.08 (64 bit)
MySQL - 5.5.49 : Database - ssm_mybatis
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssm_mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `ssm_mybatis`; /*Table structure for table `country` */ DROP TABLE IF EXISTS `country`; CREATE TABLE `country` (
`c_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '国家id',
`c_countryname` varchar(128) NOT NULL COMMENT '国家名称',
`c_capital` varchar(128) DEFAULT NULL COMMENT '国家首都名称',
PRIMARY KEY (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Data for the table `country` */ insert into `country`(`c_id`,`c_countryname`,`c_capital`) values (1,'中国','北京'),(3,'美国','华盛顿'),(4,'英国','伦敦'),(5,'日本','东京'); /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (
`u_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`u_username` varchar(64) NOT NULL COMMENT '用户名',
`u_password` varchar(64) DEFAULT NULL COMMENT '用户密码',
`u_sex` varchar(16) DEFAULT NULL COMMENT '用户性别',
`u_createTime` datetime DEFAULT NULL COMMENT '用户创建时间',
`u_cid` int(11) DEFAULT NULL COMMENT '用户国家id',
PRIMARY KEY (`u_id`),
KEY `FK_user_cid` (`u_cid`),
CONSTRAINT `FK_user_cid` FOREIGN KEY (`u_cid`) REFERENCES `country` (`c_Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; /*Data for the table `user` */ insert into `user`(`u_id`,`u_username`,`u_password`,`u_sex`,`u_createTime`,`u_cid`) values (1,'老王','','',NULL,1),(2,'jack','','',NULL,3),(3,'alice','ali111','',NULL,3),(4,'王司机','','',NULL,1),(5,'anna','ali111','',NULL,4),(6,'李师傅','','',NULL,1),(7,'漩涡鸣人','','',NULL,5),(8,'娜美','','',NULL,5),(9,'王五','abc','',NULL,1),(10,'老赵',NULL,NULL,NULL,NULL),(11,'老孙',NULL,NULL,NULL,NULL),(12,'98k',NULL,NULL,NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

ssm_mybatis.sql

JavaWeb_(Mybatis框架)MyBatis Generator简单入门-LMLPHP

package com.Gary.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;
//读取src目录下generatorConfig.xml配置文件
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);
} }

Generator.java

<?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> </generatorConfiguration>

generatorConfig.xml

  Mybatis-Generator-Config配置及生成所需文件

<!-- 配置数据库链接的包  jar包已经放到项目中 -->
<!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" 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>
<?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="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" 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>

generatorConfig.xml

  执行Generator.java代码后Refresh,可以看到Generator帮我们生成好了一系列的工程文件

JavaWeb_(Mybatis框架)MyBatis Generator简单入门-LMLPHP

package com.Gary.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;
//读取src目录下generatorConfig.xml配置文件
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);
} }

Generator.java

<?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="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> <context id="MyGenerator" targetRuntime="MyBatis3">
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_mybatis"
userId="root"
password="123456">
</jdbcConnection> <!-- JAVA JDBC类型转换 配置信息的转换规则 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 重点 javaModelGenerator javaBean配置
targetPackage 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.Gary.bean" targetProject="src">
<!-- 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.Gary.bean" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator> <!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.Gary.bean" 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>

generatorConfig.xml

  发现Generator帮我们自动生成了很多元素的注释,可以在generatorConfig.xml中配置不需要生成这些注释

      <!-- 这个标签可以去掉注释 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>

  Generator使用生成的文件操作数据库

  在user对象中生成toString()方法

  测试:

  一、按主键查询语句

    //按主键查询
User user = mapper.selectByPrimaryKey(1);
System.out.println(user);

  二、条件查询语句

  UserExample example = new UserExample();
  //将条件封装到createCriteria集合中
  example.createCriteria().andUSexEqualTo("1").andUUsernameLike("%王%");   //按条件查询
  List<User> list = mapper.selectByExample(example);   for (User user : list) {
    System.out.println(user);
  }

  三、插入数据语句

    User user = new User() ;
user.setuUsername("赵云"); mapper.insertSelective(user); session.commit();
package com.Gary.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.sikiedu.bean.User;
import com.sikiedu.bean.UserExample;
import com.sikiedu.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(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("1").andUUsernameLike("%王%"); //按条件查询
List<User> list = mapper.selectByExample(example); 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() ;
user.setuUsername("赵云"); mapper.insertSelective(user); session.commit();
} }

MapperTest.java

05-11 11:26