Mybatis简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
中文官网地址:http://www.mybatis.org/mybatis-3/zh/index.html
GitHub地址:https://github.com/mybatis/mybatis-3/tree/master/src/site
MyBatis入门
1、准备一个数据库,本例使用的是mysql数据库,建一张员工表(Employee),并且插入一条数据,sql如下:
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of employee
-- ----------------------------
BEGIN;
INSERT INTO `employee` VALUES (1, 'test', '', 'test@163.com');
COMMIT;
2、新建一个Maven工程,引入mybatis依赖以及连接mysql数据库依赖
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
3、添加Mybatis全局配置文件mybatis-config.xml,放在src/main/resources目录下,内容如下:
<?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>
<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_mybatis?allowPublicKeyRetrieval=true" />
<property name="username" value="admin" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 添加映射文件到Mybatis的全局配置文件中 -->
<mapper resource="mapper/EmployeeMapper.xml" />
</mappers>
</configuration>
4、添加映射文件EmployeeMapper.xml到src/main/resources/mapping目录下,内容如下:
<?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">
<!--
namespace:名称空间
id:唯一标识
resultType:返回值类型
#{id}:从传过来的参数中取出id值
-->
<mapper namespace="com.hd.test.mapper.EmployeeMapper">
<select id="getEmployeeById"
resultType="com.hd.test.pojo.Employee">
select id, last_name lastName, gender, email from employee where id =
#{id}
</select>
</mapper>
5、定义一个Java类Employee.java
package com.hd.test.pojo; public class Employee { private Integer id;
private String lastName;
private String gender;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", email=" + email + "]";
} }
8、一定一个测试Mybatis的Java类TestMybatis.java
package com.hd.test.mybatis; 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;
import org.junit.Test; import com.hd.test.pojo.Employee; public class TestMybatis { @Test
public void test() throws IOException {
// 1、根据mybatis全局配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
// 使用MyBatis提供的Resources类加载mybatis的配置文件,获取输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2、从SqlSession工厂中,获取sqlsession,用来执行sql
SqlSession session = sqlSessionFactory.openSession();
try {
// 查询selectOne
// @param statement Unique identifier matching the statement to use. 一个唯一标识
// @param parameter A parameter object to pass to the statement. 参数
Employee employee = (Employee) session.selectOne("com.hd.test.mapper.EmployeeMapper.getEmployeeById", 1);
// 输出信息
System.out.println(employee);
} finally {
// 关闭session
session.close();
}
} }
8、junit测试方法,输出结果:
接口式编程
1、在上例的基础上编写一个Java接口EmployeeMapper
package com.hd.test.mapper; import com.hd.test.pojo.Employee; public interface EmployeeMapper { public Employee getEmployeeById(Integer id); }
注意,sql配置文件要与接口一一对应
2、编辑测试方法内容如下:
@Test
public void test() throws IOException {
// 1、根据mybatis全局配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
// 使用MyBatis提供的Resources类加载mybatis的配置文件,获取输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 2、从SqlSession工厂中,获取sqlsession,用来执行sql
SqlSession session = sqlSessionFactory.openSession();
try {
// 3、获取接口的实现对象
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmployeeById(1);
// 输出信息
System.out.println(mapper);
System.out.println(employee);
} finally {
// 关闭session
session.close();
}
}
3、junit测试方法,输出结果: