使用MyBatis-Generator工具生成代码。
1 生成代码
1.1 在Intellij IDEA创建maven项目

1.2 添加依赖
在maven项目的pom.xml 添加 mybatis-generator-maven-plugin 插件:
<?xml version="1.0" encoding="UTF-8"?>
<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.ymqx</groupId>
<artifactId>MyBatis02</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--MySql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- JUnit单元测试工具 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mybatis-generator-core 反向生成java代码-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
<!--mybatis 代码生成插件-->
<build>
<finalName>MyBatis06</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.3 配置生成参数
在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件,作为mybatis-generator-maven-plugin 插件的执行目标:
<?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>
<!--指定特定数据库的jdbc驱动jar包的位置 -->
<classPathEntry location="D://maven//repository//mysql//mysql-connector-java//5.1.38//mysql-connector-java-5.1.38.jar"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional,旨在创建class时,对注释进行控制 -->
<commentGenerator>
<property name="suppressDate" value="true" />
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/how2java"
userId="root"
password="admin">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<javaModelGenerator targetPackage="com.ymqx.entities" targetProject="src/main/java">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="true"/>
<!-- 给Model添加一个父类 -->
<!--<property name="rootClass" value="com.ymqx.entities.BaseEntity"/>-->
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="com.ymqx.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator targetPackage="com.ymqx.mapper" targetProject="src/main/java" type="MIXEDMAPPER">
<property name="enableSubPackages" value=""/>
<!--
定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:
public;
private;
protected;
default
注意:如果 targetRuntime="MyBatis3",此参数被忽略
-->
<property name="exampleMethodVisibility" value=""/>
<!--
方法名计数器
Important note: this property is ignored if the target runtime is MyBatis3.
-->
<property name="methodNameCalculator" value=""/>
<!--
为生成的接口添加父接口
-->
<property name="rootInterface" value=""/>
</javaClientGenerator>
<table tableName="student" schema="nfmall"></table>
</context>
</generatorConfiguration>
1.4 执行生成
在Maven Projects中找到Plugins->mybatis-generator->mybatis-generator:generate

执行成功生成 entities/Student.java、entities/StudentExample.java、mapper/StudentMapper.java:

entities/Student.java:定义了POJO。
entities/StudentExample.java:定义了操作数据的条件。
mapper/StudentMapper.java:映射文件,预制了常用CRUD语句。
2 使用生成的代码
2.1 MyBatis核心配置文件
mybatisCfg.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>
<settings>
<!--设置是否允许缓存-->
<setting name="cacheEnabled" value="true"/>
<!--设置日志输出的目标-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--别名-->
<typeAliases>
<package name="com.ymqx.entities"></package>
</typeAliases>
<!--注册自定义的类型处理器-->
<typeHandlers>
<!--<typeHandler handler="" javaType="" jdbcType=""></typeHandler>-->
</typeHandlers>
<!--环境配置,default为默认选择的环境-->
<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/how2java"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--根据路径注册一个基于XML的映射器-->
<mapper resource="com/ymqx/mapper/studentMapper.xml"/>
</mappers>
</configuration>
2.2 MyBatis会话工具类
SqlSessionFactoryUtils:
package com.ymqx.utils;
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 java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
/**会话工厂*/
private static SqlSessionFactory factory;
static {
try {
/*获得配置文件的文件流*/
InputStream inputStream= Resources.getResourceAsStream("mybatisCfg.xml");
//初始化工厂
factory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获得会话对象
* 指定是否自动提交
* */
public static SqlSession openSqlSession(boolean isAutoCommit){
return getFactory().openSession(isAutoCommit);
}
public static SqlSessionFactory getFactory() {
return factory;
}
public static void setFactory(SqlSessionFactory factory) {
SqlSessionFactoryUtils.factory = factory;
}
/**
* 关闭会话
* */
public static void closeSession(SqlSession session){
if(session!=null){
session.close();
}
}
}
2.3 访问测试
studentExample对象生成查询条件:
studentExample.createCriteria().andNameLike("%a%")
Dao :
package com.ymqx;
import com.ymqx.entities.Student;
import com.ymqx.entities.StudentExample;
import com.ymqx.mapper.StudentMapper;
import com.ymqx.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Dao {
public static void main(String[] args) {
//打开一个会话
SqlSession session = SqlSessionFactoryUtils.openSqlSession(true);
//获得一个映射器
StudentMapper mapper = session.getMapper(StudentMapper.class);
StudentExample studentExample=new StudentExample();
//查询名字中含a
studentExample.createCriteria().andNameLike("%a%");
//查询多个对象,指定参数
List<Student> entities = null;
entities = mapper.selectByExample(studentExample);
for (Student student : entities) {
System.out.println(student);
}
//关闭
SqlSessionFactoryUtils.closeSession(session);
}
}
运行结果:
Logging initialized using ‘class org.apache.ibatis.logging.stdout.StdOutImpl’ adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 660143728.
==> Preparing: select id, name, sex from student WHERE ( name like ? )
==> Parameters: %a%(String)
<== Columns: id, name, sex
<== Row: 1003, jack, secret
<== Row: 1005, sala, secret
<== Row: 1006, galun, secret
<== Row: 1007, tan, secret
<== Row: 1008, jams, secret
<== Total: 5
com.ymqx.entities.Student@1f554b06
com.ymqx.entities.Student@694e1548
com.ymqx.entities.Student@1c3a4799
com.ymqx.entities.Student@131276c2
com.ymqx.entities.Student@26aa12dd
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2758fe70]
Returned connection 660143728 to pool.