1.数据库准备
创建样例表,并插入样例数据
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;
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项目
2.1 jar包依赖
在pom文件中加入一下依赖
<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>
</dependencies>
2.2 配置文件
2.2.1 mybatis-config.xml
主要配置数据库连接配置、mapper文件的路径
<?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.mybatis3.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="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>
</mappers>
</configuration>
2.2.2 StudentMapper.xml
SQL Mapper XML配置文件,mapper文件配置mapper接口方法,对应的sql语句
<?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.mybatis3.mappers.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>
元素 | 属性 | 解释 |
---|---|---|
mapper | namespace | 对应mapper接口类 全限定名 |
mapper.resultMap | type | 元素用于映射sql查询结果与model类的映射关系 对应model类 限定名 如Student |
mapper.select| insert| update。。。 | id | 对应mapper接口类的方法 |
parameterType | 指定方法的参数类型 | |
resultMap | 对应上个resultMap元素 |
2.3 代码
2.3.1 StudentMapper.java接口
接口类与 Mapper XML配置文件一一对应,此处的StudentMapper.java接口对应StudentMapper.xml,
可以发现配置文件中的namespace属性对应于接口的全限定类名
package com.mybatis3.mappers;
import java.util.List;
import com.mybatis3.domain.Student;
public interface StudentMapper
{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}
2.3.2 Student.java model类
对应于mapper.xml文件中resultmap中type指定的model类
package com.mybatis3.domain;
import java.util.Date;
public class Student
{
private Integer studId;
private String name;
private String email;
private Date dob;
// setters and getters
}
2.3.3 MyBatisSqlSessionFactory.java
工厂方法用于创建sqlSession实例,以进行与mysql的会话查询。
package com.mybatis3.util;
import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class MyBatisSqlSessionFactory
{
private static SqlSessionFactory sqlSessionFactory;
/**
* 单例模式+静态工厂方法
* 一个环境对应一个SqlSessionFactory
* */
public static SqlSessionFactory getSqlSessionFactory() {
if(sqlSessionFactory==null) {
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 会默认取用默认环境 <environments default="development">
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
// 获取session
public static SqlSession openSession() {
return getSqlSessionFactory().openSession();
}
}
2.3.4 StudentService.java
供上层调用的实现类,主要是对mybatis接口调用的封装
package com.mybatis3.services;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mybatis3.domain.Student;
import com.mybatis3.mappers.StudentMapper;
import com.mybatis3.util.MyBatisSqlSessionFactory;
public class StudentService
{
public List<Student> findAllStudents()
{
SqlSession sqlSession =
MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
} finally {
//If sqlSession is not closed
//then database Connection associated this sqlSession will not be returned to pool
//and application may run out of connections.
sqlSession.close();
}
}
public Student findStudentById(Integer studId)
{
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
} finally {
sqlSession.close();
}
}
public void createStudent(Student student)
{
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
2.3.5 junit测试类
记得在pom文件中加入junit的依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
package com.mybatis3.services;
import java.util.*;
import org.junit.*;
import com.mybatis3.domain.Student;
public class StudentServiceTest
{
private static StudentService studentService;
@BeforeClass
public static void setup(){
studentService = new StudentService();
}
@AfterClass
public static void teardown(){
studentService = null;
}
@Test
public void testFindAllStudents() {
List<Student> students = studentService.findAllStudents();
Assert.assertNotNull(students);
for (Student student : students) {
System.out.println(student);
}
}
@Test
public void testFindStudentById() {
Student student = studentService.findStudentById(1);
Assert.assertNotNull(student);
System.out.println(student);
}
@Test
public void testCreateStudent() {
Student student = new Student();
int id = 3;
student.setStudId(id);
student.setName("student_"+id);
student.setEmail("student_"+id+"gmail.com");
student.setDob(new Date());
studentService.createStudent(student);
Student newStudent = studentService.findStudentById(id);
Assert.assertNotNull(newStudent);
}
}
执行test方法,即可测试各个方法,可以debug追踪mybatis是如何通过动态代理,实现了mapper接口类。