在这里我们使用 MyBatis 开发一个简单的 Java 项目(默认你已安装JDK和MySQL及会使用Maven的基本操作),可以与上一篇通过底层操作数据进行比较
1、新建表 students,插入数据
SQL Code
1 CREATE TABLE students( 2 stud_id INT(11) NOT NULL AUTO_INCREMENT, 3 stud_name VARCHAR(50) NOT NULL, 4 stud_email VARCHAR(50) NOT NULL, 5 stud_dob DATE DEFAULT NULL, 6 PRIMARY KEY (stud_id) 7 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; 8 9 INSERT INTO students(stud_id,stud_name,stud_email,stud_dob) 10 VALUES (1,'Student1','[email protected]','1992-01-01'); 11 INSERT INTO students(stud_id,stud_name,stud_email,stud_dob) 12 VALUES (2,'Student2','[email protected]','1993-12-31');
2、新建一个Maven项目,在pom.xml中引入Mybatis.jar
2.1 创建Maven项目,名为HzMyBatis
2.2 在pom.xml中引入相应的jar包
pom.xml code
1 <dependencies> 2 <dependency> 3 <groupId>junitgroupId> 4 <artifactId>junitartifactId> 5 <version>4.11version> 6 <scope>testscope> 7 dependency> 8 <dependency> 9 <groupId>org.projectlombokgroupId> 10 <artifactId>lombokartifactId> 11 <version>1.18.2version> 12 <scope>providedscope> 13 dependency> 14 <dependency> 15 <groupId>mysqlgroupId> 16 <artifactId>mysql-connector-javaartifactId> 17 <version>5.1.39version> 18 dependency> 19 <dependency> 20 <groupId>org.mybatisgroupId> 21 <artifactId>mybatisartifactId> 22 <version>3.4.1version> 23 dependency> 24 25 <dependency> 26 <groupId>org.slf4jgroupId> 27 <artifactId>slf4j-apiartifactId> 28 <version>1.7.25version> 29 dependency> 30 <dependency> 31 <groupId>org.slf4jgroupId> 32 <artifactId>slf4j-log4j12artifactId> 33 <version>1.7.25version> 34 <scope>testscope> 35 dependency> 36 <dependency> 37 <groupId>log4jgroupId> 38 <artifactId>log4jartifactId> 39 <version>1.2.17version> 40 dependency> 41 dependencies>说明:mysql-connector-java-5.1.39 mysql数据库的驱动包、mybatis-3.4.1 Mybatis包、lombok-1.18.2 减少重复代码量(getter/setter/toString等需要注解标注)
3、新建 mybatis-config.xml 和映射器 StudentMapper.xml 配置文件
mybatis-config.xml:包括数据库连接信息,类型别名等信息
StudentMapper.xml:映射的SQL语句
这两个xml文件需要放到classpath路径下
mybatis-config.xml Code
1 xml version="1.0" encoding="UTF-8"?> 2 DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 4 <configuration> 5 6 <typeAliases> 7 <typeAlias alias="Student" type="com.hz.mybatis.bean.Student" /> 8 typeAliases> 9 10 11 <environments default="development"> 12 <environment id="development"> 13 14 <transactionManager type="JDBC" /> 15 <dataSource type="POOLED"> 16 <property name="driver" value="com.mysql.jdbc.Driver" /> 17 <property name="url" value="jdbc:mysql://127.0.0.1:3306/hadoop" /> 18 <property name="username" value="root" /> 19 <property name="password" value="root" /> 20 dataSource> 21 environment> 22 environments> 23 24 25 <mappers> 26 <mapper resource="com/hz/mybatis/mapper/StudentMapper.xml" /> 27 mappers> 28 configuration>
StudentMapper.xml Code
1 xml version="1.0" encoding="UTF-8"?> 2 DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="com.hz.mybatis.mapper.StudentMapper"> 6 <resultMap type="Student" id="StudentResult"> 7 <id property="studId" column="stud_id" /> 8 <result property="name" column="stud_name" /> 9 <result property="email" column="stud_email" /> 10 <result property="dob" column="stud_dob" /> 11 resultMap> 12 13 <select id="findAllStudents" resultMap="StudentResult"> 14 SELECT * FROM STUDENTS 15 select> 16 17 <select id="findStudentById" parameterType="java.lang.Integer" resultType="Student"> 18 SELECT STUD_ID AS STUDID, STUD_NAME AS NAME, STUD_EMAIL AS EMAIL, STUD_DOB AS DOB FROM STUDENTS WHERE STUD_ID = #{Id} 19 select> 20 21 <insert id="insertStudent" parameterType="Student"> 22 INSERT INTO STUDENTS(STUD_ID, STUD_NAME,STUD_EMAIL,STUD_DOB) 23 VALUES(#{studId}, #{name}, #{email}, #{dob}) 24 insert> 25 mapper>
3、新建 MyBatisSqlSessionFactory 单例模式类
MyBatisSqlSessionFactory.java Code
import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * 创建单例SqlSessionFactory * @author DONG * */ 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 (Exception e) { e.printStackTrace(); } } return sqlSessionFactory; } }
4、新建映射器 StudentMapper 接口和 StudentService 类
创建一个 StudentMapper 接口,其定义的方法名和在 Mapper XML 配置文件定义的 SQL 映射语 句名称相同
创建一个 StudentService.java 类,包含了一些业务操作的实现
1、首先, 创建 JavaBean Student.java
Student.java Code
1 import java.util.Date; 2 3 import lombok.Data; 4 5 @Data 6 public class Student { 7 8 private Integer studId; 9 private String name; 10 private String email; 11 private Date dob; 12 13 }2、创建映射器 Mapper 接口 StudentMapper.java 其方法签名和 StudentMapper.xml 中定义的 SQL 映射定义名
相同StudentMapper.java Code
1 import java.util.List; 2 3 import com.hz.mybatis.bean.Student; 4 5 public interface StudentMapper { 6 ListfindAllStudents(); 7 Student findStudentById(Integer id); 8 void insertStudent(Student student); 9 } 3、现在创建 MyBatisStudentService.java 实现对表 students 的数据库操作
1 import java.util.List; 2 3 import org.apache.ibatis.session.SqlSession; 4 import org.slf4j.Logger; 5 import org.slf4j.LoggerFactory; 6 7 import com.hz.mybatis.bean.Student; 8 import com.hz.mybatis.mapper.StudentMapper; 9 import com.hz.mybatis.util.MyBatisSqlSessionFactory; 10 11 /** 12 * 学生业务操作 13 * @author DONG 14 * 15 */ 16 public class MyBatisStudentService { 17 18 private static Logger logger = LoggerFactory.getLogger(MyBatisStudentService.class); 19 20 /** 21 * 查询所有学生信息 22 * @return 23 */ 24 public ListfindAllStudents(){ 25 SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); 26 logger.debug("获取sqlSession信息: ", sqlSession); 27 try { 28 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 29 return studentMapper.findAllStudents(); 30 } finally { 31 sqlSession.close(); 32 } 33 } 34 35 /** 36 * 通过学生ID查询学生信息 37 * @param studId 38 * @return 39 */ 40 public Student findStudentById(Integer studId){ 41 logger.debug("通过学生ID查询学生信息: ", studId); 42 43 SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); 44 45 try { 46 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 47 return studentMapper.findStudentById(studId); 48 } finally { 49 sqlSession.close(); 50 } 51 } 52 53 /** 54 * 插入学生信息 55 */ 56 public void insertStudent(Student student){ 57 SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); 58 59 try { 60 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 61 studentMapper.insertStudent(student); 62 } finally { 63 sqlSession.close(); 64 } 65 66 } 67 }
5、新建一个 JUnit 测试类来测试 MyBatisStudentService
1 import java.util.List; 2 3 import org.junit.AfterClass; 4 import org.junit.BeforeClass; 5 import org.junit.Test; 6 7 import com.hz.mybatis.bean.Student; 8 import com.hz.mybatis.service.MyBatisStudentService; 9 10 /** 11 * 测试 12 * @author DONG 13 * 14 */ 15 public class TestStudentMapper { 16 17 private static MyBatisStudentService studentService; 18 19 @BeforeClass 20 public static void setup(){ 21 studentService = new MyBatisStudentService(); 22 } 23 24 @AfterClass 25 public static void teardown(){ 26 studentService = null; 27 } 28 29 @Test 30 public void testFindAllStudents(){ 31 Liststudents = studentService.findAllStudents(); 32 33 for (Student student : students) { 34 System.out.println(student); 35 } 36 } 37 }