全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

第一个 MyBatis 程序

下面从零开始编写第一个 MyBatis 查询程序。

创建实体类

Java
// User.java
package com.example.entity;

public class User {
    private Integer id;
    private String username;
    private String email;
    
    // getter 和 setter 省略
    @Override
    public String toString() {
        return "User{id=" + id + ", username='" + username + "', email='" + email + "'}";
    }
}

创建 Mapper 接口

Java
// UserMapper.java
package com.example.mapper;

import com.example.entity.User;

public interface UserMapper {
    User selectById(Integer id);
}

创建 XML 映射文件

XML
<!-- 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.example.mapper.UserMapper">
    
    <select id="selectById" resultType="com.example.entity.User">
        SELECT id, username, email FROM user WHERE id = #{id}
    </select>
    
</mapper>

注意:namespace 必须与 Mapper 接口全限定名一致,id 必须与接口方法名一致。

注册映射文件

mybatis-config.xml 中注册:

XML
<mappers>
    <mapper resource="mapper/UserMapper.xml"/>
</mappers>

执行程序

Java
// Main.java
public class Main {
    public static void main(String[] args) throws IOException {
        // 1. 加载配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        // 2. 构建 SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        // 3. 获取 SqlSession
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 4. 获取 Mapper 代理对象
            UserMapper mapper = session.getMapper(UserMapper.class);
            
            // 5. 执行查询
            User user = mapper.selectById(1);
            System.out.println(user);
        }
    }
}

执行流程总结

  1. 加载 mybatis-config.xml 构建 SqlSessionFactory
  2. 通过 openSession() 获取 SqlSession
  3. 通过 getMapper() 获取接口代理对象
  4. 调用接口方法执行 SQL
  5. MyBatis 自动将结果集映射到 Java 对象

注意:SqlSession 使用后必须关闭,推荐使用 try-with-resources 自动关闭。

要点总结

  • 创建实体类、Mapper 接口、XML 映射文件三件套
  • namespace 与接口全限定名对应,id 与方法名对应
  • 执行流程:配置 → SqlSessionFactory → SqlSession → getMapper → 调用方法
  • SqlSession 使用后必须关闭

文章存放路径:articles/MYBATIS/入门/MyBatis 概述与环境搭建/第一个 MyBatis 程序.md

📝 发现内容有误?点击此处直接编辑

← 上一篇 开发环境搭建
下一篇 → configuration 元素结构
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库