相比較傳統的JDBC,使用Mybatis的好處在於省略了獲取和釋放數據庫鏈接,準備PreparedStatement,向SQL中插入參數等代html
碼,使開發人員更加關注於數據持久代碼的開發。本篇博客就從經過一個Demo來說解如何使用Mybatis這個簡單易用的持久層解決方案。java
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=utf8; /*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');
項目結構如圖所示:
mysql
pom.xml文件爲:sql
<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.learn</groupId> <artifactId>mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <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> </project>
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> <typeAliases> <typeAlias alias="Student" type="com.learn.mybatis_demo.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/mybatis" /> <property name="username" value="root" /> <property name="password" value="sa12345" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/learn/mybatis_demo/mappers/StudentMapper.xml" /> </mappers> </configuration>
StudentMapper.xml文件爲:apache
<?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.learn.mybatis_demo.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=#{studId} </select> <insert id="insertStudent" parameterType="Student"> INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob}) </insert> </mapper>
package com.learn.mybatis_demo.util; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; 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(); } }
package com.learn.mybatis_demo.domain; import java.util.Date; public class Student { private Integer studId; private String name; private String email; private Date dob; public Integer getStudId() { return studId; } public void setStudId(Integer studId) { this.studId = studId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } }
package com.learn.mybatis_demo.mappers; import java.util.List; import com.learn.mybatis_demo.domain.Student; public interface StudentMapper { List<Student> findAllStudents(); Student findStudentById(Integer id); void insertStudent(Student student); }
package com.learn.mybatis_demo.service; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.learn.mybatis_demo.domain.Student; import com.learn.mybatis_demo.mappers.StudentMapper; import com.learn.mybatis_demo.util.MyBatisSqlSessionFactory; public class StudentService { private Logger logger = LoggerFactory.getLogger(getClass()); public List<Student> findAllStudents() { SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try { StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); return studentMapper.findAllStudents(); } finally { sqlSession.close(); } } Student findStudentById(Integer studId) { logger.debug("Select Student By ID :{}", studId); SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try { StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); return studentMapper.findStudentById(studId); } finally { sqlSession.close(); } } void createStudent(Student student) { SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try { StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); studentMapper.insertStudent(student); sqlSession.commit(); } finally { sqlSession.close(); } } }
package com.learn.mybatis_demo.service; import java.util.Date; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.learn.mybatis_demo.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); } }