Mybatis 简介
MyBatis 是一款优秀的持久层框架, 它支持定制化 SQL, 存储过程以及高级映射. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集. MyBatis 可以使用简单的 xml 或注解来配置和映射原生信息, 将接口和 Java 的 POJOs(Plain Old Java Objects, 普通的 Java 对象) 映射成数据库中的记录.
中文官网地址: http://www.mybatis.org/mybatis-3/zh/index.html
GitHub 地址:
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', '1', '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 测试方法, 输出结果:
来源: http://www.bubuko.com/infodetail-2894119.html