參考書籍
原著:Java Persistence with MyBatis 3. 作者:K.Siva Prasad Reddy.
譯著:Java持久化之Mybatis3. 作者:婁孌.
mybatisDemo:基于myeclipse10,mysql,jdk1.7替废,mybatis3.2.2
項目結構
程序源碼
步驟:
- 新建表 STUDENTS吧黄,插入樣本數(shù)據(jù)
- 新建一個 Java 項目剂买,將 MyBatis-3.2.2.jar 添加到 classpath 中
- 新建建 MyBatisSqlSessionFactory 單例模式類
- 新建映射器 StudentMapper 接口和 StudentService 類
- 新建一個 JUnit 測試類來測試 StudentService
1.新建表 STUDENTS,插入樣本數(shù)據(jù)
使用以下 SQL 腳本往 MySQL 數(shù)據(jù)庫中創(chuàng)建 STUDENTS 表插入樣本數(shù)據(jù):
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)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*Sample Data for the students table */
insert into students(stud_id,name,email,dob)
values (1,'Student1','student1@gmail.com','1983-06-25');
insert into students(stud_id,name,email,dob)
values (2,'Student2','student2@gmail.com','1983-06-25');
2.新建一個 Java Maven項目,修改pom.xml
文件為:
<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>look</groupId>
<artifactId>mybatisDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. 新建 log4j.properties 文件,添加到 classpath 中
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
4.新建 mybatis-config.xml 和映射器 StudentMapper.xml 配置文件
- 創(chuàng)建 MyBatis 的主要配置文件 mybatis-config.xml,其中包括數(shù)據(jù)庫連接信息瘟栖,類型別名等等,然后將其加到 classpath 中谅阿;
<?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>
<typeAliases>
<typeAlias alias="Student" type="com.look.domain.Student" />
</typeAliases>
<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/test" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/look/mapper/StudentMapper.xml" />
</mappers>
</configuration>
- 創(chuàng)建 SQL 映射器 XML 配置文件 StudentMapper.xml 并且將它放在 com.look.mapper 包中
<?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.look.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>
上述的 StudentMapper,xml 文件包含的映射的 SQL 語句可以通過 ID 加上名空間調(diào)用半哟。
5.新建 MyBatisSqlSessionFactory 單例類
新建 MyBatisSqlSessionFactory.java 類文件,實例化它签餐,使其持有一個 SqlSessionFactory 單例對象:
package com.look.util;
import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
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();
}
}
上述的代碼段中寓涨,我們創(chuàng)建了一個 SqlSessionFactory 對象,我們將使用它來獲得 SqlSession 對象和執(zhí)行映射的SQL 語句氯檐。
6.新建 StudentMapper 接口和 StudentService 類
創(chuàng)建一個 StudentMapper 接口戒良,其定義的方法名和在 Mapper XML 配置文件定義的 SQL 映射語句名稱相同;
在創(chuàng)建一個 StudentService.java 類冠摄,包含了一些業(yè)務操作的實現(xiàn)糯崎。
首先, 創(chuàng)建 JavaBean Student.java
創(chuàng)建映射器 Mapper 接口 StudentMapper.java 其方法簽名和 StudentMapper.xml 中定義的 SQL 映射定義名相同
現(xiàn)在創(chuàng)建 StudentService.java 實現(xiàn)對表 STUDENTS 的數(shù)據(jù)庫操作
你也可以通過不通過 Mapper 接口執(zhí)行映射的 SQL 語句。
Student student = (Student)sqlSession.
selectOne("com.look.mapper.StudentMapper.findStudentById",
studId);
然而河泳,使用 Mapper 接口是最佳實踐沃呢,我們可以以類型安全的方式調(diào)用映射的 SQL 語句。
7.新建一個 JUnit 測試類來測試 StudentService27
新建一個 JUnit 測試類測試 StudentSerivce.java 中定義的方法
8. 它是怎么工作的
首先拆挥,我們配置了 MyBatis 最主要的配置文件-mybatis-config.xml,里面包含了 JDBC 連接參數(shù)薄霜;配置了映射器Mapper XML 配置文件文件,里面包含了 SQL 語句的映射纸兔。
我們使用 mybatis-config.xml 內(nèi)的信息創(chuàng)建了 SqlSessionFactory 對象惰瓜。每個數(shù)據(jù)庫環(huán)境應該就一個
SqlSessionFactory 對象實例,所以我們使用了單例模式只創(chuàng)建一個 SqlSessionFactory 實例汉矿。
我們創(chuàng)建了一個映射器 Mapper 接口-StudentMapper崎坊,其定義的方法簽名和在 StudentMapper.xml 中定義的完全一樣(即映射器 Mapper 接口中的方法名跟 StudentMapper.xml 中的 id 的值相同)。注意 StudentMapper.xml 中namespace 的值被設置成 com.mybatis3.mappers.StudentMapper负甸,是 StudentMapper 接口的完全限定名流强。這使我們可以使用接口來調(diào)用映射的 SQL 語句。
在 StudentService.java 中呻待,我們在每一個方法中創(chuàng)建了一個新的 SqlSession打月,并在方法功能完成后關閉
SqlSession。每一個線程應該有它自己的 SqlSession 實例蚕捉。 SqlSession 對象實例不是線程安全的奏篙,并且不被共享。所以 SqlSession 的作用域最好就是其所在方法的作用域。從 Web 應用程序角度上看秘通,SqlSession 應該存在于 request 級別作用域上为严。