讲给Android程序员看的前端系列教程(40集免费视频教程+源码)
版权声明
- 本文原创作者:谷哥的小弟
- 作者博客地址:http://blog.csdn.net/lfdfhl
概述
MyBatis逆向工程,简称MBG。它是一个专门为MyBatis框架使用者定制的代码生成器,它可以快速的根据表生成对应的映射文件xxxMapper.xml,接口xxxMapper.java,以及JavaBean类对象。
接下来,我们以示例的形式学习MBG的使用。
数据准备
DROP DATABASE IF EXISTS mybatisDatabase;
CREATE DATABASE mybatisDatabase;
use mybatisDatabase;
CREATE TABLE user(
id INT PRIMARY KEY auto_increment,
name VARCHAR(50),
password VARCHAR(50),
gender VARCHAR(10)
);
CREATE TABLE student(
id INT PRIMARY KEY auto_increment,
name VARCHAR(50),
address VARCHAR(50),
gender VARCHAR(10)
);
INSERT INTO user(name,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(name,password,gender) VALUES("momo","234567","female");
INSERT INTO user(name,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(name,password,gender) VALUES("pepe","456123","female");
INSERT INTO student(name,address,gender) VALUES("tome","BeiJing","female");
INSERT INTO student(name,address,gender) VALUES("dodo","ChengDu","female");
INSERT INTO student(name,address,gender) VALUES("mbmb","ZhangYe","female");
INSERT INTO student(name,address,gender) VALUES("zxzx","BaoDing","female");
SELECT * FROM user;
SELECT * FROM student;
搭建开发环境
创建普通的Java工程,结构如下:
在lib中一共存在四个jar包:
- log4j-1.2.17.jar
- mybatis-3.4.1.jar
- mybatis-generator-core-1.3.2.jar
- mysql-connector-java-5.1.7-bin.jar
其中,mybatis-generator-core-1.3.2.jar专门用于MyBatis逆向工程
log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
generatorConfig.xml
在工程Mybatis012根目录下创建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>
<!--
targetRuntime 配置生成的版本
1、MyBatis3 功能完整版本
2、MyBatis3Simple 怎删改查标准版
-->
<context id="MySQLTables" targetRuntime="MyBatis3Simple">
<!-- 去掉自动生成的代码的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据源 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatisDatabase"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--
javaModelGenerator 配置生成模型JavaBean
1、targetPackage 生成的JavaBean的包名
2、targetProject 生成的JavaBean的存放路径,该值常为.\src
-->
<javaModelGenerator targetPackage="cn.com.pojo" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--
sqlMapGenerator 配置生成的映射文件xxxMapper.xml
1、targetPackage 生成的xxxMapper.xml的包名
2、targetProject 生成的xxxMapper.xml的存放路径,该值常为.\src
-->
<sqlMapGenerator targetPackage="cn.com.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--
javaClientGenerator 配置生成的xxxMapper.java接口
1、targetPackage 生成的xxxMapper.java的包名
2、targetProject 生成的xxxMapper.java的存放路径,该值常为.\src
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.com.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 配置表和JavaBean的对应关系-->
<table tableName="user" domainObjectName="User" ></table>
<table tableName="student" domainObjectName="Student" ></table>
</context>
</generatorConfiguration>
Generator
在cn.com.generator包下建立Generator,其内容如下:
package cn.com.generator;
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;
//读取generatorConfig.xml配置文件
File configFile = new File("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工程即可见自动生成的代码,图示如下:
mybatis-config.xml
在自动生成代码后再创建并配置mybatis-config.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">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatisDatabase" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 通过指定包的方式配置mapper -->
<package name="cn.com.mapper" />
</mappers>
</configuration>
MybatisTest
创建MybatisTest测试该逆向工程,其代码如下:
package cn.com.test;
import java.io.InputStream;
import java.util.Iterator;
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 cn.com.mapper.StudentMapper;
import cn.com.mapper.UserMapper;
import cn.com.pojo.Student;
import cn.com.pojo.User;
/**
* 本文作者:谷哥的小弟
* 博客地址:http://blog.csdn.net/lfdfhl
*/
public class MybatisTest {
static SqlSessionFactory sqlSessionFactory = null;
public static SqlSessionFactory getSqlSessionFactory() {
try {
if (sqlSessionFactory == null) {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}
return sqlSessionFactory;
} catch (Exception e) {
// TODO: handle exception
} finally {
}
return null;
}
@Test
public void testUser() {
//获取SqlSession
SqlSession sqlSession=getSqlSessionFactory().openSession();
//利用SqlSession得到Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.selectAll();
Iterator<User> iterator = userList.iterator();
while(iterator.hasNext()) {
User user = iterator.next();
System.out.println(user.getName()+" , "+user.getGender());
}
//关闭SqlSession
sqlSession.close();
}
@Test
public void testStudent() {
//获取SqlSession
SqlSession sqlSession=getSqlSessionFactory().openSession();
//利用SqlSession得到Mapper
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.selectByPrimaryKey(1);
System.out.println(student.getName()+" , "+student.getGender());
//关闭SqlSession
sqlSession.close();
}
}
测试结果如下:
附图
在此,附上整个项目的结构图,图示如下: