第 1 章:MyBatis 简介
1.1 关于 MyBatis
MyBatis 本是 apache 的一个开源项目 iBatis, 2010 年这个项目由 apache software
foundation 迁移到了 google code,并且改名为 MyBatis 。2013 年 11 月迁移到 Github。
https://github.com/mybatis/mybatis-3
MyBatis 通过抽像底层的 JDBC 代码,自动化 SQL 结果集产生 Java 对象,Java 对象的数
据持久化数据库中的过程,使得对 SQL 的使用变量容易
MyBatis 是一个半自动化的 ORM 框架,需要手工匹配提供 POJO、SQL 和映射关系
Hibernate 是一个全自动化的 ORM 框架,深层次封装,全表映射、对多表关联和复杂
SQL 查询支持较差,性能相对较差
为什么选择 MyBatis
它消除了大量的 JDBC 冗余代码
它有低的学习曲线
它能很好地与传统数据库协同工作
它可以接受 SQL 语句
它性能更好
容易与第三方框架集成
1.2 第一个 MyBatis 程序
step1:新 s students 表
CREATE TABLE STUDENTS
(
stud_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(50) NOT NULL,
dob date DEFAULT NULL,
PRIMARY KEY (stud_id)
) ;
insert into students(stud_id,name,email,dob)
values (1,'Student1','[email protected]','1983-06-25');
insert into students(stud_id,name,email,dob)
values (2,'Student2','[email protected]','1983-06-25');
step2:导入 jar
mybatis-3.x.x.jar
slf4j-api-1.7.5.jar
slf-log4j12-1.7.5.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.22.jar
pom.xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
step3:新建 s mybatis 配置文件 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>
<properties resource="application.properties"/>
<typeAliases>
<package name="com.oracle.mybatis.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/oracle/mybatis/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
step4:新建映射文件
public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.oracle.mybatis.mapper.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id" />
<result property="name" column="name" />
<result property="email" column="email" />
<result property="dob" column="dob" />
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
SELECT * FROM STUDENTS
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
FROM STUDENTS WHERE STUD_ID=#{Id}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
VALUES(#{studId },#{name},#{email},#{dob})
</insert>
</mapper>
Step5:得到 SqlSessionFactory
public class MyBatisSqlSessionFactory
{
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory()
{
if(sqlSessionFactory == null)
{
InputStream inputStream;
try
{
inputStream = Resources.
getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new
SqlSessionFactoryBuilder().build(inputStream);
}
catch (IOException e)
{
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
public static SqlSession openSession()
{
return getSqlSessionFactory().openSession();
}
}
step6:得到 sqlSession
SqlSession sqlSession =MyBatisSqlSessionFactory.openSession();
StudentMapper studentMapper =sqlSession.getMapper(StudentMapper.class);
1.3MyBatis 核心 API
org.apache.ibatis.session.Configuration 将 xml 解析到 Configuration 对像中,以便复用
SqlSessionFactoryBuilder 根据配置信息或代码生成 SqlSessionFactory
SqlSessionFactory 生成 SqlSession(会话的)工厂,两个实现类 DefaultSqlSessionFactory 和
SqlSessionManager(目前没有使用),默认使用 DefaultSqlSessionFactory,可以使用 XML
和代码构建
SqlSession 可以发送 SQL 去执行并返回结果,也可以获取 Mapper 接口
SQL Mapper 是 MyBatis 新设计的组件,它是由一个 java 接口和 XML 文件(或注解)构
成的,需要给出对应的 SQL 和映射规则,它负责发送 SQL,并返回结果
1.4 构建 SqlSessionFactory
1.4.1 用 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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers></configuration>
String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = Re
sources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
1.4.2 用代码构建
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
1.5 创建 SqlSession
在 MyBatis 中 SqlSession 接口的实现类有两个,DefaultSqlSesion 和 SqlSessionManager,
SqlSession 类似 JDBC 中的 Connection 接口,用完后保证释放
SqlSession session = sqlSessionFactory.openSession();
try {
//....
session.commit();
} catch(Exception e)
{
session.rollback();
}finally {
session.close();
}
1.6 映射器
映射器是由 java 接口和 XML 文件(或注解)共同组成的,它的作用如下:
定义参数类型
描述缓存
描述 SQL 语句
定义查询结果和 POJO 的映射关系
其实映射器就是通过 XML 和反射实来动态实现的 java 接口的实现类