C语言自学完备手册(33篇)
Android多分辨率适配框架
JavaWeb核心技术系列教程
HTML5前端开发实战系列教程
MySQL数据库实操教程(35篇图文版)
推翻自己和过往——自定义View系列教程(10篇)
走出思维困境,踏上精进之路——Android开发进阶精华录
讲给Android程序员看的前端系列教程(40集免费视频教程+源码)
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包:
其中,mybatis-generator-core-1.3.2.jar专门用于MyBatis逆向工程
# 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
在工程Mybatis012根目录下创建generatorConfig.xml,图示如下:
其内容如下:
<generatorConfiguration>
<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 targetPackage="cn.com.pojo" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="cn.com.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.com.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
javaClientGenerator>
<table tableName="user" domainObjectName="User" >table>
<table tableName="student" domainObjectName="Student" >table>
context>
generatorConfiguration>
在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文件,其内容如下:
<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>
<package name="cn.com.mapper" />
mappers>
configuration>
创建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();
}
}