如何使用 MyBatis 开发一个简单的 Java 项目:
- 新建表 STUDENTS,插入样本数据
- 新建一个 Java 项目,将 MyBatis-3.2.2.jar 添加到 classpath 中
- 新建建 MyBatisSqlSessionFactory 单例模式类
- 新建映射器 StudentMapper 接口和 StudentService 类
- 新建一个 JUnit 测试类来测试 StudentService
1 CREATE TABLE STUDENTS 2 ( 3 stud_id int(11) NOT NULL AUTO_INCREMENT, 4 name varchar(50) NOT NULL, 5 email varchar(50) NOT NULL, 6 dob date DEFAULT NULL, 7 PRIMARY KEY (stud_id) 8 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; 9 /*Sample Data for the students table */ 10 insert into students(stud_id,name,email,dob) 11 values (1,‘Student1‘,‘student1@gmail.com‘,‘1983-06-25‘); 12 insert into students(stud_id,name,email,dob) 13 values (2,‘Student2‘,‘student2@gmail.com‘,‘1983-06-25‘);
1. 创建一个 Java 项目,名为 mybatis-demo.
2. 如果你没有使用类似于 Maven 和 Gradle 之类的依赖管理构建工具,你需要手动下载这些依赖的 JAR 包,手动添加到 classpath 中.
3. 你可以从 http://code.google.com/p/mybatis 上下载 MyBatis 的发布包 mybatis-3.2.2.zip。这个包包
含了 mybatis-3.2.2.jar 文件和它的可选的依赖包如 slf4j/log4j 日志 jar 包.
4. 我们将使用 SLF4J 日志记录框架 和 log4j 一起记录日志。mybatis-3.2.2.zip 包含了 slf4j 这个依赖 jar包。
5. 解压 mybatis-3.2.2.zip 文件,将 mybatis-3.2.2.jar,lib/slf4j-api-1.7.5.jar, lib/slf-log4j12-1.7.5.jar,和 lib/log4j-1.2.17.jar 这些 jar 包添加到 classpath 中
6. 你可以从http://junit.org上 下 载JUnit JAR文 件 , 从
http://www.mysql.com/downloads/connector/j/ 上下载 MySQL 数据库驱动
7. 将 junit-4.11.jar 和 mysql-connector-java-5.1.22.jar 添加到 classpath 中
8. 如果你正在使用 maven,配置这些 jar 包依赖就变得简单多了。在你的 pom.xml 中添加以下依赖即可:
<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>
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
<?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="entity.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="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/StudentMapper.xml" /> </mappers> </configuration>
<?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="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>
上述的 StudentMapper,xml 文件包含的映射的 SQL 语句可以通过 ID 加上名空间调用。
package 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(); } }
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 }
package mappers; import java.util.List; import entity.Student; public interface StudentMapper { List<Student> findAllStudents(); Student findStudentById(Integer id); void insertStudent(Student student); }
package services; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import entity.Student; import mappers.StudentMapper; import 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 { //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) { 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(); } } public void createStudent(Student student) { SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try { StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); studentMapper.insertStudent(student); sqlSession.commit(); } finally { sqlSession.close(); } } }
import java.util.*; import org.junit.*; import entity.Student; import services.StudentService; public class StudentTest { 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); } }
完成!!!
首先,我们配置了 MyBatis 最主要的配置文件-mybatis-config.xml,里面包含了 JDBC 连接参数;配置了映射器Mapper XML 配置文件文件,里面包含了 SQL 语句的映射。我们使用 mybatis-config.xml 内的信息创建了 SqlSessionFactory 对象。每个数据库环境应该就一个SqlSessionFactory 对象实例,所以我们使用了单例模式只创建一个 SqlSessionFactory 实例。我们创建了一个映射器 Mapper 接口-StudentMapper,其定义的方法签名和在 StudentMapper.xml 中定义的完全一样(即映射器 Mapper 接口中的方法名跟 StudentMapper.xml 中的 id 的值相同)。注意 StudentMapper.xml 中namespace 的值被设置成 com.mybatis3.mappers.StudentMapper,是 StudentMapper 接口的完全限定名。这使我们可以使用接口来调用映射的 SQL 语句。在 StudentService.java 中,我们在每一个方法中创建了一个新的 SqlSession,并在方法功能完成后关闭SqlSession。每一个线程应该有它自己的 SqlSession 实例。SqlSession 对象实例不是线程安全的,并且不被共享。所以 SqlSession 的作用域最好就是其所在方法的作用域。从 Web 应用程序角度上看,SqlSession 应该存在于 request 级别作用域上。
原文:https://www.cnblogs.com/yangf428/p/12257613.html