MyBatis学习笔记-快速使用

MyBatis官方文档:https://mybatis.org/mybatis-3/

完整目录结构如下
在这里插入图片描述

1. 创建数据库表

首先创建一个User表,便于之后的测试

建表语句

create database `mybatis`;

use `mybatis`;

create table `user` (
	`id` int(20) not null,
    `name` varchar(30) default null,
    `pwd` varchar(30) default null
)engine = innodb default charset = utf8;

insert into `user`(`id`, `name`, `pwd`) values
(1,'a','123456'),
(2,'b','123456'),
(3,'c','123456')

user 表中内容

user表中内容

2 导入依赖包

新建一个maven项目,pom.xml中导入相关的包

<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.10</version>
</dependency>
<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>
<!--junit测试-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
    <scope>test</scope>
</dependency>

3 数据库连接配置

在 mybatis-config.xml 中可以对 MyBatis 进行配置

官方配置文档:https://mybatis.org/mybatis-3/zh/configuration.html

下面是一个数据库连接的配置例子

<?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.cj.jdbc.Driver"/>
                
                <!--mysql8 的url中需要指定时区,否则会出现中文乱码-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

4 获取 SqlSession 封装

将官网提供的下面三行代码封装成工具类 MyBatisUtils,便于获取 sqlSession 实例

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public class MyBatisUtils {
    private static final SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "org/mybatis/example/mybatis-config.xml";
        InputStream inputStream = null;
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

5 编写实体类和接口

实体类 User

public class User {
    private int id;
    private String name;
    private String pwd;

    // 省略 getter 和 setter 方法

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + pwd + '\'' +
                '}';
    }
}

UserMapper 接口

public interface UserMapper {
    List<User> getUserList();
}

6 XML 定义 SQL 映射

userMapper.xml

<?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.zhao.dao.UserMapper">
    <select id="getUserList" resultType="com.zhao.pojo.User">
        select * from user
    </select>
</mapper>

7 Mapper 注册

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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--mapper 注册-->
    <mappers>
        <mapper resource="com/zhao/dao/userMapper.xml"/>
    </mappers>
</configuration>

8 Maven 资源过滤配置

maven 项目默认资源是在 resources 目录下

如果目标资源文件在其他目录下,比如userMapper 就在 src/main/java目录下,需要在配置 resources,

pom.xml

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

9 测试执行 SQL

通过 SqlSession 实例来直接执行已映射的 SQL 语句

方式一

try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}

方式二(推荐)

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

注意:确保 SqlSession 在finally代码中或try-resource中被关闭

public class UserMapperTest extends TestCase {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();;
    public void testGetUserList() {
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userMapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } finally {
          sqlSession.close();
        }
    }
}
posted @ 2022-07-04 18:05  油虾条  阅读(22)  评论(0编辑  收藏  举报