湖泊 發表於 2026-4-7 09:00:00

Mybatis基础操作

<h2 id="mybatis基础使用">Mybatis基础使用</h2>
<h3 id="mybatis编程式开发">Mybatis编程式开发</h3>
<ol>
<li>mybatis和MySQL jar包依赖</li>
</ol>
<pre><code class="language-xml">&lt;dependencies&gt;
    &lt;!-- MyBatis 核心 --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mybatis&lt;/groupId&gt;
      &lt;artifactId&gt;mybatis&lt;/artifactId&gt;
      &lt;version&gt;3.5.10&lt;/version&gt;
    &lt;/dependency&gt;
   
    &lt;!-- MySQL 驱动 --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;8.0.33&lt;/version&gt;
    &lt;/dependency&gt;
   
    &lt;!-- 连接池(可选,推荐) --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.zaxxer&lt;/groupId&gt;
      &lt;artifactId&gt;HikariCP&lt;/artifactId&gt;
      &lt;version&gt;5.0.1&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<ol start="2">
<li>全局配置文件mybatis-config.xml</li>
</ol>
<p>配置文件对应标签可以看官方文档:https://mybatis.org/mybatis-3/configuration.html</p>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;
&lt;configuration&gt;
   
    &lt;!-- 1. 加载外部属性文件 --&gt;
    &lt;properties resource="jdbc.properties"/&gt;
   
    &lt;!-- 2. 全局设置 --&gt;
    &lt;settings&gt;
      &lt;!-- 开启下划线到驼峰命名自动映射 --&gt;
      &lt;setting name="mapUnderscoreToCamelCase" value="true"/&gt;
      &lt;!-- 开启二级缓存 --&gt;
      &lt;setting name="cacheEnabled" value="true"/&gt;
      &lt;!-- 延迟加载的触发方法 --&gt;
      &lt;setting name="lazyLoadTriggerMethods" value=""/&gt;
      &lt;!-- 查询时,关闭关联对象即时加载 --&gt;
      &lt;setting name="lazyLoadingEnabled" value="true"/&gt;
      &lt;!-- 设置超时时间 --&gt;
      &lt;setting name="defaultStatementTimeout" value="3000"/&gt;
      &lt;!-- 使用列标签代替列名 --&gt;
      &lt;setting name="useColumnLabel" value="true"/&gt;
      &lt;!-- 允许JDBC支持自动生成主键 --&gt;
      &lt;setting name="useGeneratedKeys" value="true"/&gt;
    &lt;/settings&gt;
   
    &lt;!-- 3. 类型别名配置 --&gt;
    &lt;typeAliases&gt;
      &lt;!-- 扫描包,自动注册别名 --&gt;
      &lt;package name="com.example.entity"/&gt;
      &lt;!-- 也可以单独配置 --&gt;
      &lt;!-- &lt;typeAlias type="com.example.entity.User" alias="User"/&gt; --&gt;
    &lt;/typeAliases&gt;
   
    &lt;!-- 4. 环境配置(可配置多个,通过default属性切换) --&gt;
    &lt;environments default="development"&gt;
      &lt;!-- 开发环境 --&gt;
      &lt;environment id="development"&gt;
            &lt;!-- 事务管理器 --&gt;
            &lt;transactionManager type="JDBC"&gt;
                &lt;property name="closeConnection" value="false"/&gt;
            &lt;/transactionManager&gt;
            
            &lt;!-- 数据源配置 --&gt;
            &lt;dataSource type="POOLED"&gt;
                &lt;property name="driver" value="${jdbc.driver}"/&gt;
                &lt;property name="url" value="${jdbc.url}"/&gt;
                &lt;property name="username" value="${jdbc.username}"/&gt;
                &lt;property name="password" value="${jdbc.password}"/&gt;
                &lt;!-- 连接池配置 --&gt;
                &lt;property name="poolMaximumActiveConnections" value="20"/&gt;
                &lt;property name="poolMaximumIdleConnections" value="10"/&gt;
                &lt;property name="poolMaximumCheckoutTime" value="20000"/&gt;
                &lt;property name="poolTimeToWait" value="20000"/&gt;
            &lt;/dataSource&gt;
      &lt;/environment&gt;
      
      &lt;!-- 测试环境 --&gt;
      &lt;environment id="test"&gt;
            &lt;transactionManager type="JDBC"/&gt;
            &lt;dataSource type="POOLED"&gt;
                &lt;property name="driver" value="${jdbc.driver}"/&gt;
                &lt;property name="url" value="${jdbc.test.url}"/&gt;
                &lt;property name="username" value="${jdbc.test.username}"/&gt;
                &lt;property name="password" value="${jdbc.test.password}"/&gt;
            &lt;/dataSource&gt;
      &lt;/environment&gt;
    &lt;/environments&gt;
   
    &lt;!-- 5. 映射器配置 --&gt;
    &lt;mappers&gt;
      &lt;!-- 方式1:通过resource指定XML文件 --&gt;
      &lt;mapper resource="com/example/mapper/UserMapper.xml"/&gt;
      
      &lt;!-- 方式2:通过class指定接口(需要接口和XML同名同路径) --&gt;
      &lt;!-- &lt;mapper class="com.example.mapper.UserMapper"/&gt; --&gt;
      
      &lt;!-- 方式3:扫描包下所有mapper接口 --&gt;
      &lt;!-- &lt;package name="com.example.mapper"/&gt; --&gt;
    &lt;/mappers&gt;
&lt;/configuration&gt;
</code></pre>
<ol start="3">
<li>映射器 Mapper.xml</li>
</ol>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;
&lt;mapper namespace="com.example.mapper.UserMapper"&gt;
   
    &lt;!-- 基础ResultMap映射 --&gt;
    &lt;resultMap id="BaseResultMap" type="User"&gt;
      &lt;id property="id" column="id"/&gt;
      &lt;result property="username" column="username"/&gt;
      &lt;result property="password" column="password"/&gt;
      &lt;result property="email" column="email"/&gt;
      &lt;result property="age" column="age"/&gt;
      &lt;result property="status" column="status"/&gt;
      &lt;result property="createTime" column="create_time"/&gt;
      &lt;result property="updateTime" column="update_time"/&gt;
      &lt;!-- 枚举类型处理 --&gt;
      &lt;result property="gender" column="gender"
                typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/&gt;
    &lt;/resultMap&gt;
   
    &lt;!-- 包含订单的ResultMap(一对多) --&gt;
    &lt;resultMap id="UserWithOrdersResultMap" type="User" extends="BaseResultMap"&gt;
      &lt;!-- 一对多关联:用户的订单 --&gt;
      &lt;collection property="orders" ofType="Order" column="id"
                  select="com.example.mapper.OrderMapper.selectByUserId"/&gt;
    &lt;/resultMap&gt;
   
    &lt;!-- 插入用户 --&gt;
    &lt;insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id"&gt;
      INSERT INTO users (username, password, email, age, status, create_time, update_time, gender)
      VALUES (#{username}, #{password}, #{email}, #{age}, #{status}, #{createTime}, #{updateTime},
                #{gender, typeHandler=org.apache.ibatis.type.EnumOrdinalTypeHandler})
    &lt;/insert&gt;
   
    &lt;!-- 批量插入用户 --&gt;
    &lt;insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id"&gt;
      INSERT INTO users (username, password, email, age, status, create_time, update_time)
      VALUES
      &lt;foreach collection="list" item="user" separator=","&gt;
            (#{user.username}, #{user.password}, #{user.email}, #{user.age},
             #{user.status}, #{user.createTime}, #{user.updateTime})
      &lt;/foreach&gt;
    &lt;/insert&gt;
   
    &lt;!-- 根据ID删除 --&gt;
    &lt;delete id="deleteById" parameterType="Long"&gt;
      DELETE FROM users WHERE id = #{id}
    &lt;/delete&gt;
   
    &lt;!-- 根据用户名删除 --&gt;
    &lt;delete id="deleteByUsername" parameterType="String"&gt;
      DELETE FROM users WHERE username = #{username}
    &lt;/delete&gt;
   
    &lt;!-- 更新用户 --&gt;
    &lt;update id="update" parameterType="User"&gt;
      UPDATE users
      &lt;set&gt;
            &lt;if test="username != null"&gt;username = #{username},&lt;/if&gt;
            &lt;if test="password != null"&gt;password = #{password},&lt;/if&gt;
            &lt;if test="email != null"&gt;email = #{email},&lt;/if&gt;
            &lt;if test="age != null"&gt;age = #{age},&lt;/if&gt;
            &lt;if test="status != null"&gt;status = #{status},&lt;/if&gt;
            &lt;if test="updateTime != null"&gt;update_time = #{updateTime},&lt;/if&gt;
      &lt;/set&gt;
      WHERE id = #{id}
    &lt;/update&gt;
   
    &lt;!-- 更新用户状态 --&gt;
    &lt;update id="updateStatus"&gt;
      UPDATE users SET status = #{status} WHERE id = #{id}
    &lt;/update&gt;
   
    &lt;!-- 根据ID查询 --&gt;
    &lt;select id="selectById" parameterType="Long" resultMap="BaseResultMap"&gt;
      SELECT * FROM users WHERE id = #{id}
    &lt;/select&gt;
   
    &lt;!-- 查询所有用户 --&gt;
    &lt;select id="selectAll" resultMap="BaseResultMap"&gt;
      SELECT * FROM users ORDER BY create_time DESC
    &lt;/select&gt;
   
    &lt;!-- 根据用户名查询(模糊查询) --&gt;
    &lt;select id="selectByUsername" parameterType="String" resultMap="BaseResultMap"&gt;
      SELECT * FROM users
      WHERE username LIKE CONCAT('%', #{username}, '%')
    &lt;/select&gt;
   
    &lt;!-- 条件查询(动态SQL) --&gt;
    &lt;select id="selectByCondition" parameterType="map" resultMap="BaseResultMap"&gt;
      SELECT * FROM users
      &lt;where&gt;
            &lt;if test="username != null and username != ''"&gt;
                AND username LIKE CONCAT('%', #{username}, '%')
            &lt;/if&gt;
            &lt;if test="email != null and email != ''"&gt;
                AND email = #{email}
            &lt;/if&gt;
            &lt;if test="minAge != null"&gt;
                AND age &gt;= #{minAge}
            &lt;/if&gt;
            &lt;if test="maxAge != null"&gt;
                AND age &amp;lt;= #{maxAge}
            &lt;/if&gt;
            &lt;if test="status != null"&gt;
                AND status = #{status}
            &lt;/if&gt;
            &lt;if test="startTime != null"&gt;
                AND create_time &gt;= #{startTime}
            &lt;/if&gt;
            &lt;if test="endTime != null"&gt;
                AND create_time &amp;lt;= #{endTime}
            &lt;/if&gt;
      &lt;/where&gt;
      ORDER BY id DESC
    &lt;/select&gt;
   
    &lt;!-- 分页查询 --&gt;
    &lt;select id="selectByPage" resultMap="BaseResultMap"&gt;
      SELECT * FROM users
      ORDER BY id DESC
      LIMIT #{offset}, #{pageSize}
    &lt;/select&gt;
   
    &lt;!-- 统计数量 --&gt;
    &lt;select id="count" resultType="int"&gt;
      SELECT COUNT(*) FROM users
    &lt;/select&gt;
   
    &lt;!-- 查询用户及其订单(关联查询) --&gt;
    &lt;select id="selectUserWithOrders" parameterType="Long" resultMap="UserWithOrdersResultMap"&gt;
      SELECT * FROM users WHERE id = #{userId}
    &lt;/select&gt;
&lt;/mapper&gt;
</code></pre>
<ol start="4">
<li>Mapper接口</li>
</ol>
<pre><code class="language-java">package com.example.mapper;

import com.example.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
* User 数据访问接口
* 注意:不使用Spring时,这个接口不需要添加@Repository等注解
*/
public interface UserMapper {
   
    // ========== 增 ==========
   
    /**
   * 插入用户
   */
    int insert(User user);
   
    /**
   * 批量插入用户
   */
    int batchInsert(List&lt;User&gt; users);
   
    // ========== 删 ==========
   
    /**
   * 根据ID删除用户
   */
    int deleteById(Long id);
   
    /**
   * 根据用户名删除用户
   */
    int deleteByUsername(String username);
   
    // ========== 改 ==========
   
    /**
   * 更新用户
   */
    int update(User user);
   
    /**
   * 更新用户状态
   * 使用@Param注解指定参数名
   */
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);
   
    // 使用注解定义SQL(不需要在XML中配置)
    @Update("UPDATE users SET age = #{age} WHERE id = #{id}")
    int updateAge(@Param("id") Long id, @Param("age") Integer age);
   
    // ========== 查 ==========
   
    /**
   * 根据ID查询用户
   */
    User selectById(Long id);
   
    /**
   * 查询所有用户
   */
    List&lt;User&gt; selectAll();
   
    /**
   * 根据用户名查询
   */
    List&lt;User&gt; selectByUsername(String username);
   
    /**
   * 条件查询
   * @param condition 查询条件
   */
    List&lt;User&gt; selectByCondition(Map&lt;String, Object&gt; condition);
   
    /**
   * 分页查询
   * @param pageNum 页码
   * @param pageSize 每页大小
   */
    List&lt;User&gt; selectByPage(@Param("offset") int offset, @Param("pageSize") int pageSize);
   
    /**
   * 统计用户数量
   */
    int count();
   
    /**
   * 使用注解定义查询
   */
    @Select("SELECT * FROM users WHERE email = #{email}")
    User selectByEmail(String email);
   
    /**
   * 关联查询:查询用户及其订单(一对多)
   * 需要在XML中配置resultMap
   */
    User selectUserWithOrders(Long userId);
}
</code></pre>
<ol start="5">
<li>mybatis工具类</li>
</ol>
<pre><code class="language-java">package com.example.app;

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 java.io.IOException;
import java.io.InputStream;

/**
* MyBatis 工具类 - 手动管理 SqlSessionFactory
*/
public class MyBatisUtil {
   
    private static SqlSessionFactory sqlSessionFactory;
   
    // 静态代码块,在类加载时初始化
    static {
      try {
            // 1. 加载 MyBatis 配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            
            // 2. 创建 SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            
            System.out.println("MyBatis SqlSessionFactory 初始化成功!");
      } catch (IOException e) {
            System.err.println("MyBatis 初始化失败: " + e.getMessage());
            throw new RuntimeException("MyBatis 初始化失败", e);
      }
    }
   
    /**
   * 获取 SqlSession 对象
   */
    public static SqlSession getSqlSession() {
      return sqlSessionFactory.openSession();
    }
   
    /**
   * 获取 SqlSession 对象(自动提交事务)
   */
    public static SqlSession getSqlSessionWithAutoCommit() {
      return sqlSessionFactory.openSession(true);
    }
   
    /**
   * 关闭 SqlSession
   */
    public static void closeSession(SqlSession session) {
      if (session != null) {
            session.close();
      }
    }
   
    /**
   * 获取 SqlSessionFactory
   */
    public static SqlSessionFactory getSqlSessionFactory() {
      return sqlSessionFactory;
    }
   
    /**
   * 获取 Mapper 接口的代理对象
   */
    public static &lt;T&gt; T getMapper(Class&lt;T&gt; type) {
      try (SqlSession session = getSqlSession()) {
            return session.getMapper(type);
      }
    }
}
</code></pre>
<ol start="6">
<li>编程式使用示例</li>
</ol>
<pre><code class="language-java">package com.example.app;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 不使用 Spring 时,MyBatis 编程式使用示例
*/
public class MyBatisDemo {
   
    public static void main(String[] args) {
      // 示例1:基础用法
      basicUsage();
      
      // 示例2:事务管理
      transactionManagement();
      
      // 示例3:动态SQL
      dynamicSqlExample();
      
      // 示例4:批量操作
      batchOperation();
      
      // 示例5:手动构建 SqlSessionFactory
      manualSqlSessionFactory();
    }
   
    /**
   * 示例1:基础CRUD操作
   */
    private static void basicUsage() {
      System.out.println("=== 示例1:基础CRUD操作 ===");
      
      SqlSession sqlSession = null;
      try {
            // 1. 获取 SqlSession
            sqlSession = MyBatisUtil.getSqlSession();
            
            // 2. 获取 Mapper 接口的代理对象
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            // 3. 插入数据
            User newUser = new User();
            newUser.setUsername("zhangsan");
            newUser.setPassword("123456");
            newUser.setEmail("zhangsan@example.com");
            newUser.setAge(25);
            newUser.setStatus(1);
            newUser.setCreateTime(new Date());
            newUser.setUpdateTime(LocalDateTime.now());
            
            int insertResult = userMapper.insert(newUser);
            System.out.println("插入结果:" + insertResult + ",生成ID:" + newUser.getId());
            
            // 4. 查询数据
            User user = userMapper.selectById(newUser.getId());
            System.out.println("查询用户:" + user);
            
            // 5. 更新数据
            user.setEmail("updated@example.com");
            int updateResult = userMapper.update(user);
            System.out.println("更新结果:" + updateResult);
            
            // 6. 分页查询
            List&lt;User&gt; userList = userMapper.selectByPage(0, 10);
            System.out.println("分页查询结果:" + userList.size() + " 条");
            
            // 7. 统计
            int count = userMapper.count();
            System.out.println("总用户数:" + count);
            
            // 8. 提交事务
            sqlSession.commit();
            System.out.println("事务提交成功");
            
      } catch (Exception e) {
            // 回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            System.err.println("操作失败:" + e.getMessage());
            e.printStackTrace();
      } finally {
            // 关闭 SqlSession
            MyBatisUtil.closeSession(sqlSession);
      }
    }
   
    /**
   * 示例2:事务管理
   */
    private static void transactionManagement() {
      System.out.println("\n=== 示例2:事务管理 ===");
      
      SqlSession sqlSession = null;
      try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            // 开启事务(默认不会自动提交)
            
            // 操作1:插入用户
            User user1 = new User("lisi", "lisi@example.com");
            user1.setPassword("123456");
            user1.setCreateTime(new Date());
            userMapper.insert(user1);
            
            // 操作2:模拟业务逻辑异常
            if (user1.getUsername().equals("lisi")) {
                throw new RuntimeException("模拟业务异常,事务应该回滚");
            }
            
            // 操作3:更新用户(不会执行,因为上面抛出异常)
            userMapper.updateAge(user1.getId(), 30);
            
            // 提交事务
            sqlSession.commit();
            System.out.println("事务提交成功");
            
      } catch (Exception e) {
            if (sqlSession != null) {
                sqlSession.rollback();
                System.out.println("事务回滚:" + e.getMessage());
            }
      } finally {
            MyBatisUtil.closeSession(sqlSession);
      }
    }
   
    /**
   * 示例3:动态SQL和条件查询
   */
    private static void dynamicSqlExample() {
      System.out.println("\n=== 示例3:动态SQL和条件查询 ===");
      
      try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            // 构建查询条件
            Map&lt;String, Object&gt; condition = new HashMap&lt;&gt;();
            condition.put("username", "zhang");// 模糊查询
            condition.put("minAge", 20);         // 年龄 &gt;= 20
            condition.put("maxAge", 30);         // 年龄 &lt;= 30
            condition.put("status", 1);          // 状态为启用
            
            List&lt;User&gt; users = userMapper.selectByCondition(condition);
            System.out.println("条件查询结果:" + users.size() + " 条记录");
            
            for (User user : users) {
                System.out.println(user);
            }
            
            sqlSession.commit();
      } catch (Exception e) {
            e.printStackTrace();
      }
    }
   
    /**
   * 示例4:批量操作
   */
    private static void batchOperation() {
      System.out.println("\n=== 示例4:批量操作 ===");
      
      SqlSession sqlSession = null;
      try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            // 批量插入
            List&lt;User&gt; users = createTestUsers(5);
            int result = userMapper.batchInsert(users);
            System.out.println("批量插入:" + result + " 条记录");
            
            sqlSession.commit();
            
      } catch (Exception e) {
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
      } finally {
            MyBatisUtil.closeSession(sqlSession);
      }
    }
   
    /**
   * 示例5:手动构建 SqlSessionFactory
   */
    private static void manualSqlSessionFactory() {
      System.out.println("\n=== 示例5:手动构建 SqlSessionFactory ===");
      
      String resource = "mybatis-config.xml";
      try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
            
            // 1. 手动构建 SqlSessionFactoryBuilder
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            
            // 2. 构建 SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
            
            // 3. 从 SqlSessionFactory 中获取 SqlSession
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
               
                // 4. 获取 Mapper
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
               
                // 5. 执行查询
                List&lt;User&gt; users = userMapper.selectAll();
                System.out.println("手动构建查询结果:" + users.size() + " 条记录");
               
                // 6. 手动提交事务
                sqlSession.commit();
            }
            
      } catch (Exception e) {
            e.printStackTrace();
      }
    }
   
    /**
   * 创建测试用户
   */
    private static List&lt;User&gt; createTestUsers(int count) {
      List&lt;User&gt; users = new java.util.ArrayList&lt;&gt;();
      for (int i = 1; i &lt;= count; i++) {
            User user = new User();
            user.setUsername("test" + i);
            user.setPassword("pass" + i);
            user.setEmail("test" + i + "@example.com");
            user.setAge(20 + i);
            user.setStatus(1);
            user.setCreateTime(new Date());
            users.add(user);
      }
      return users;
    }
}
</code></pre>
<h3 id="整合spring">整合Spring</h3>
<ol>
<li>添加依赖</li>
</ol>
<p>较编程式开发主要是需要添加spring核心和MyBatis-Spring整合包</p>
<pre><code class="language-xml">&lt;dependencies&gt;
    &lt;!-- Spring 核心依赖 --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
   
    &lt;!-- MyBatis-Spring 整合包(关键!) --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mybatis&lt;/groupId&gt;
      &lt;artifactId&gt;mybatis-spring&lt;/artifactId&gt;
      &lt;version&gt;${mybatis.spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<ol start="2">
<li><strong>mybatis.xml</strong>​ - MyBatis 和事务配置</li>
</ol>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd"&gt;

    &lt;!-- 导入数据源配置 --&gt;
    &lt;import resource="datasource.xml"/&gt;
   
    &lt;!-- 1. 配置 SqlSessionFactory --&gt;
    &lt;bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&gt;
      &lt;!-- 引用数据源 --&gt;
      &lt;property name="dataSource" ref="dataSource"/&gt;
      
      &lt;!-- MyBatis 主配置文件路径(如果有的话) --&gt;
      &lt;property name="configLocation" value="classpath:mybatis-config.xml"/&gt;
      
      &lt;!-- 实体类别名包 --&gt;
      &lt;property name="typeAliasesPackage" value="com.example.entity"/&gt;
      
      &lt;!-- MyBatis 映射文件路径 --&gt;
      &lt;property name="mapperLocations"&gt;
            &lt;array&gt;
                &lt;value&gt;classpath:com/example/dao/mapper/*.xml&lt;/value&gt;
            &lt;/array&gt;
      &lt;/property&gt;
      
      &lt;!-- MyBatis 全局配置 --&gt;
      &lt;property name="configuration"&gt;
            &lt;bean class="org.apache.ibatis.session.Configuration"&gt;
                &lt;!-- 下划线转驼峰 --&gt;
                &lt;property name="mapUnderscoreToCamelCase" value="true"/&gt;
                &lt;!-- 开启二级缓存 --&gt;
                &lt;property name="cacheEnabled" value="true"/&gt;
                &lt;!-- 使用列标签代替列名 --&gt;
                &lt;property name="useColumnLabel" value="true"/&gt;
                &lt;!-- 延迟加载的触发方法 --&gt;
                &lt;property name="lazyLoadTriggerMethods"&gt;
                  &lt;array&gt;
                        &lt;value&gt;equals&lt;/value&gt;
                        &lt;value&gt;clone&lt;/value&gt;
                        &lt;value&gt;hashCode&lt;/value&gt;
                        &lt;value&gt;toString&lt;/value&gt;
                  &lt;/array&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
      &lt;/property&gt;
      
      &lt;!-- 插件配置 --&gt;
      &lt;property name="plugins"&gt;
            &lt;array&gt;
                &lt;!-- 分页插件示例 --&gt;
                &lt;!--
                &lt;bean class="com.github.pagehelper.PageInterceptor"&gt;
                  &lt;property name="properties"&gt;
                        &lt;props&gt;
                            &lt;prop key="helperDialect"&gt;mysql&lt;/prop&gt;
                        &lt;/props&gt;
                  &lt;/property&gt;
                &lt;/bean&gt;
                --&gt;
            &lt;/array&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
   
    &lt;!-- 2. 配置 Mapper 扫描器(方式一:扫描包) --&gt;
    &lt;bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&gt;
      &lt;!-- 扫描的包路径 --&gt;
      &lt;property name="basePackage" value="com.example.dao"/&gt;
      &lt;!-- 可选:指定 SqlSessionFactory --&gt;
      &lt;property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/&gt;
      &lt;!-- 可选:指定注解,只有标记了指定注解的接口才会被扫描 --&gt;
      &lt;!-- &lt;property name="annotationClass" value="org.springframework.stereotype.Repository"/&gt; --&gt;
    &lt;/bean&gt;
   
    &lt;!-- 3. 配置事务管理器 --&gt;
    &lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;
      &lt;property name="dataSource" ref="dataSource"/&gt;
    &lt;/bean&gt;
   
    &lt;!-- 4. 开启注解驱动的事务管理 --&gt;
    &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
   
    &lt;!-- 5. 事务AOP配置(可选,如果使用注解则不需要) --&gt;
    &lt;!--
    &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt;
      &lt;tx:attributes&gt;
            &lt;tx:method name="get*" read-only="true" propagation="SUPPORTS"/&gt;
            &lt;tx:method name="find*" read-only="true" propagation="SUPPORTS"/&gt;
            &lt;tx:method name="select*" read-only="true" propagation="SUPPORTS"/&gt;
            &lt;tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/&gt;
      &lt;/tx:attributes&gt;
    &lt;/tx:advice&gt;
   
    &lt;aop:config&gt;
      &lt;aop:pointcut id="serviceMethods" expression="execution(* com.example.service.*.*(..))"/&gt;
      &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/&gt;
    &lt;/aop:config&gt;
    --&gt;
   
    &lt;!-- 6. 配置 SqlSessionTemplate(可选,如果需要在DAO中直接使用) --&gt;
    &lt;bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"&gt;
      &lt;constructor-arg index="0" ref="sqlSessionFactory"/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<ol start="3">
<li><strong>applicationContext.xml</strong>​ - Spring 主配置文件</li>
</ol>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd"&gt;

    &lt;!-- 开启注解扫描 --&gt;
    &lt;context:component-scan base-package="com.example"&gt;
      &lt;!-- 排除 Controller,如果使用 MVC 的话 --&gt;
      &lt;context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller"/&gt;
    &lt;/context:component-scan&gt;
   
    &lt;!-- 导入 MyBatis 配置 --&gt;
    &lt;import resource="classpath:spring/mybatis.xml"/&gt;
   
    &lt;!-- 其他 Bean 配置 --&gt;
    &lt;bean id="userService" class="com.example.service.impl.UserServiceImpl"/&gt;
   
    &lt;!-- 属性占位符配置 --&gt;
    &lt;context:property-placeholder location="classpath:*.properties"/&gt;
&lt;/beans&gt;
</code></pre>
<ol start="4">
<li>测试案例</li>
</ol>
<pre><code class="language-java">package com.example.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.example")
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement
public class AppConfig {
   
    @Bean
    public DataSource dataSource(
            @Value("${jdbc.driverClassName}") String driverClassName,
            @Value("${jdbc.url}") String url,
            @Value("${jdbc.username}") String username,
            @Value("${jdbc.password}") String password) {
      
      BasicDataSource dataSource = new BasicDataSource();
      dataSource.setDriverClassName(driverClassName);
      dataSource.setUrl(url);
      dataSource.setUsername(username);
      dataSource.setPassword(password);
      dataSource.setInitialSize(5);
      dataSource.setMaxTotal(20);
      return dataSource;
    }
   
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
      SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
      factoryBean.setDataSource(dataSource);
      factoryBean.setTypeAliasesPackage("com.example.entity");
      
      // 配置 MyBatis
      org.apache.ibatis.session.Configuration configuration =
            new org.apache.ibatis.session.Configuration();
      configuration.setMapUnderscoreToCamelCase(true);
      factoryBean.setConfiguration(configuration);
      
      // 设置映射文件位置
      Resource[] mapperLocations = new Resource[]{
            new ClassPathResource("com/example/dao/mapper/*.xml")
      };
      factoryBean.setMapperLocations(mapperLocations);
      
      return factoryBean;
    }
   
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
      MapperScannerConfigurer scanner = new MapperScannerConfigurer();
      scanner.setBasePackage("com.example.dao");
      scanner.setSqlSessionFactoryBeanName("sqlSessionFactory");
      return scanner;
    }
   
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
      return new DataSourceTransactionManager(dataSource);
    }
}
</code></pre>
<h3 id="整合springboot">整合SpringBoot</h3>
<ol>
<li>添加依赖</li>
</ol>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;
    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;
    &lt;version&gt;3.0.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;mysql&lt;/groupId&gt;
    &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;!-- 无需显式添加连接池,Spring Boot 默认使用 HikariCP --&gt;
</code></pre>
<ol start="2">
<li>​ <code>application.yml</code>配置,无需创建<code>mybatis-config.xml</code>文件,可直接在yaml文件中配置</li>
</ol>
<pre><code class="language-yaml">spring:
datasource:
    url: jdbc:mysql://localhost:3306/testdb
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5

mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: com.example.entity
configuration:
    map-underscore-to-camel-case: true
</code></pre>
<ol start="3">
<li>配置自动扫描 Mapper 接口</li>
</ol>
<pre><code class="language-java">@SpringBootApplication
@MapperScan("com.example.mapper") // 自动扫描 Mapper 接口
public class Application {
    public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
    }
}
</code></pre>
<ol start="4">
<li>自动注入 Mapper</li>
</ol>
<pre><code class="language-java">@Service
public class UserService {
    @Autowired
    private UserMapper userMapper; // 直接注入
   
    public User getUser(Long id) {
      return userMapper.selectById(id); // 直接使用
    }
}
</code></pre>
<h2 id="mybatis代码生成器">Mybatis代码生成器</h2>
<p>https://github.com/mybatis/generator</p>
<h2 id="mybatis动态sql">Mybatis动态sql</h2>
<p>https://mybatis.org/mybatis-3/dynamic-sql.html</p>
<h2 id="mybatis批量操作">Mybatis批量操作</h2>
<p>进行批量操作时,有三种方式,操作方式对比:</p>
<table>
<thead>
<tr>
<th>操作类型</th>
<th>适用场景</th>
<th>实现方式</th>
<th>优点</th>
<th>缺点</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>foreach SQL</strong>​</td>
<td>小批量数据插入/更新/删除</td>
<td>在 XML 中写 <code>&lt;foreach&gt;</code>生成 SQL</td>
<td>简单直观,一次性执行</td>
<td>SQL 长度有限制,大数据量可能超限</td>
</tr>
<tr>
<td><strong>Batch Executor</strong>​</td>
<td>大批量数据操作</td>
<td>使用 <code>ExecutorType.BATCH</code></td>
<td>性能最优,预编译 SQL</td>
<td>需要手动管理事务和提交</td>
</tr>
<tr>
<td><strong>JDBC Batch</strong>​</td>
<td>需要底层控制</td>
<td>使用原生 JDBC Batch</td>
<td>完全控制,灵活性高</td>
<td>代码复杂,需处理底层细节</td>
</tr>
</tbody>
</table>
<h3 id="使用-foreach-标签的批量操作案例">使用 foreach 标签的批量操作案例</h3>
<h4 id="批量插入">批量插入</h4>
<pre><code class="language-xml">&lt;!-- 1. 基本批量插入 --&gt;
&lt;insert id="batchInsert" parameterType="java.util.List"&gt;
    INSERT INTO users (username, email, age, status, create_time)
    VALUES
    &lt;foreach collection="list" item="user" separator=","&gt;
      (#{user.username}, #{user.email}, #{user.age}, #{user.status}, NOW())
    &lt;/foreach&gt;
&lt;/insert&gt;

&lt;!-- 2. 批量插入(返回自增主键) --&gt;
&lt;insert id="batchInsertWithKeys" parameterType="java.util.List"
      useGeneratedKeys="true" keyProperty="id"&gt;
    INSERT INTO users (username, email, age, status, create_time)
    VALUES
    &lt;foreach collection="list" item="user" separator=","&gt;
      (#{user.username}, #{user.email}, #{user.age}, #{user.status}, #{user.createTime})
    &lt;/foreach&gt;
&lt;/insert&gt;

&lt;!-- 3. 批量插入或更新(MySQL ON DUPLICATE KEY UPDATE) --&gt;
&lt;insert id="batchInsertOrUpdate" parameterType="java.util.List"&gt;
    INSERT INTO users (username, email, age, status, create_time)
    VALUES
    &lt;foreach collection="list" item="user" separator=","&gt;
      (#{user.username}, #{user.email}, #{user.age}, #{user.status}, #{user.createTime})
    &lt;/foreach&gt;
    ON DUPLICATE KEY UPDATE
    email = VALUES(email),
    age = VALUES(age),
    status = VALUES(status),
    update_time = NOW()
&lt;/insert&gt;
</code></pre>
<h4 id="批量更新">批量更新</h4>
<pre><code class="language-xml">&lt;!-- 1. 批量更新(根据ID) --&gt;
&lt;update id="batchUpdate" parameterType="java.util.List"&gt;
    UPDATE users
    &lt;trim prefix="SET" suffixOverrides=","&gt;
      &lt;trim prefix="username = CASE" suffix="END,"&gt;
            &lt;foreach collection="list" item="user"&gt;
                &lt;if test="user.username != null"&gt;
                  WHEN id = #{user.id} THEN #{user.username}
                &lt;/if&gt;
            &lt;/foreach&gt;
      &lt;/trim&gt;
      &lt;trim prefix="email = CASE" suffix="END,"&gt;
            &lt;foreach collection="list" item="user"&gt;
                &lt;if test="user.email != null"&gt;
                  WHEN id = #{user.id} THEN #{user.email}
                &lt;/if&gt;
            &lt;/foreach&gt;
      &lt;/trim&gt;
      &lt;trim prefix="age = CASE" suffix="END,"&gt;
            &lt;foreach collection="list" item="user"&gt;
                &lt;if test="user.age != null"&gt;
                  WHEN id = #{user.id} THEN #{user.age}
                &lt;/if&gt;
            &lt;/foreach&gt;
      &lt;/trim&gt;
      &lt;trim prefix="status = CASE" suffix="END,"&gt;
            &lt;foreach collection="list" item="user"&gt;
                &lt;if test="user.status != null"&gt;
                  WHEN id = #{user.id} THEN #{user.status}
                &lt;/if&gt;
            &lt;/foreach&gt;
      &lt;/trim&gt;
      update_time = NOW()
    &lt;/trim&gt;
    WHERE id IN
    &lt;foreach collection="list" item="user" open="(" separator="," close=")"&gt;
      #{user.id}
    &lt;/foreach&gt;
&lt;/update&gt;

&lt;!-- 2. 批量更新(简单版,逐条更新) --&gt;
&lt;update id="batchUpdateSimple"&gt;
    &lt;foreach collection="list" item="user" separator=";"&gt;
      UPDATE users
      &lt;set&gt;
            &lt;if test="user.username != null"&gt;username = #{user.username},&lt;/if&gt;
            &lt;if test="user.email != null"&gt;email = #{user.email},&lt;/if&gt;
            &lt;if test="user.age != null"&gt;age = #{user.age},&lt;/if&gt;
            update_time = NOW()
      &lt;/set&gt;
      WHERE id = #{user.id}
    &lt;/foreach&gt;
&lt;/update&gt;

&lt;!-- 3. 批量更新状态 --&gt;
&lt;update id="batchUpdateStatus"&gt;
    UPDATE users
    SET status = #{status},
      update_time = NOW()
    WHERE id IN
    &lt;foreach collection="ids" item="id" open="(" separator="," close=")"&gt;
      #{id}
    &lt;/foreach&gt;
&lt;/update&gt;
</code></pre>
<h4 id="批量删除">批量删除</h4>
<pre><code class="language-xml">&lt;!-- 1. 批量删除(根据ID列表) --&gt;
&lt;delete id="batchDeleteByIds"&gt;
    DELETE FROM users
    WHERE id IN
    &lt;foreach collection="ids" item="id" open="(" separator="," close=")"&gt;
      #{id}
    &lt;/foreach&gt;
&lt;/delete&gt;

&lt;!-- 2. 批量删除(根据条件) --&gt;
&lt;delete id="batchDeleteByCondition"&gt;
    DELETE FROM users
    WHERE (username, email) IN
    &lt;foreach collection="list" item="user" open="(" separator="," close=")"&gt;
      (#{user.username}, #{user.email})
    &lt;/foreach&gt;
&lt;/delete&gt;
</code></pre>
<h4 id="批量查询">批量查询</h4>
<pre><code class="language-xml">&lt;!-- 1. 批量查询(根据ID列表) --&gt;
&lt;select id="batchSelectByIds" resultMap="BaseResultMap"&gt;
    SELECT * FROM users
    WHERE id IN
    &lt;foreach collection="ids" item="id" open="(" separator="," close=")"&gt;
      #{id}
    &lt;/foreach&gt;
    ORDER BY
    &lt;foreach collection="ids" item="id" separator=","&gt;
      id = #{id} DESC
    &lt;/foreach&gt;
&lt;/select&gt;

&lt;!-- 2. 批量查询(分页批量查询) --&gt;
&lt;select id="batchSelectByPage" parameterType="map" resultMap="BaseResultMap"&gt;
    SELECT * FROM users
    WHERE id IN
    &lt;foreach collection="ids" item="id" open="(" separator="," close=")"&gt;
      #{id}
    &lt;/foreach&gt;
    LIMIT #{offset}, #{pageSize}
&lt;/select&gt;
</code></pre>
<h3 id="使用-foreach-标签的注意事项">使用 foreach 标签的注意事项</h3>
<h4 id="sql-长度限制">SQL 长度限制</h4>
<pre><code class="language-java">/**
* 处理超长 SQL 的批量操作
*/
public int safeBatchInsert(List&lt;User&gt; userList) {
    int batchSize = 1000; // 根据数据库配置调整
    int total = 0;
   
    for (int i = 0; i &lt; userList.size(); i += batchSize) {
      int end = Math.min(i + batchSize, userList.size());
      List&lt;User&gt; subList = userList.subList(i, end);
      
      // 检查 SQL 长度
      String sql = generateInsertSQL(subList);
      if (sql.length() &gt; 1000000) { // 1MB
            // 进一步减小批次
            batchSize = batchSize / 2;
            i -= batchSize; // 回退
            continue;
      }
      
      total += userMapper.batchInsert(subList);
    }
   
    return total;
}
</code></pre>
<h4 id="事务管理">事务管理</h4>
<pre><code class="language-java">@Service
public class UserBatchService {
   
    @Transactional(rollbackFor = Exception.class)
    public int batchInsertWithTransaction(List&lt;User&gt; userList) {
      int result = 0;
      
      try {
            result = userMapper.batchInsert(userList);
            
            // 如果后续操作失败,整个事务回滚
            someOtherOperation();
            
      } catch (Exception e) {
            // 抛出异常触发回滚
            throw new RuntimeException("批量插入失败,已回滚", e);
      }
      
      return result;
    }
   
    /**
   * 手动控制事务
   */
    public int batchInsertManualTransaction(List&lt;User&gt; userList) {
      // 获取事务定义
      DefaultTransactionDefinition def = new DefaultTransactionDefinition();
      def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
      
      // 获取事务状态
      TransactionStatus status = transactionManager.getTransaction(def);
      
      try {
            int result = userMapper.batchInsert(userList);
            
            // 提交事务
            transactionManager.commit(status);
            return result;
            
      } catch (Exception e) {
            // 回滚事务
            transactionManager.rollback(status);
            throw new RuntimeException("批量操作失败,已回滚", e);
      }
    }
}
</code></pre>
<h2 id="mybatis关联查询和延迟加载">Mybatis关联查询和延迟加载</h2>
<table>
<thead>
<tr>
<th>特性</th>
<th>嵌套查询(Nested Query)</th>
<th>嵌套结果(Nested Result)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>原理</strong>​</td>
<td>执行多条SQL查询,在结果映射中引用其他查询</td>
<td>执行一条联合查询,在结果映射中处理嵌套对象</td>
</tr>
<tr>
<td><strong>SQL数量</strong>​</td>
<td>N+1 条(主查询 + N 条关联查询)</td>
<td>1 条(联合查询)</td>
</tr>
<tr>
<td><strong>性能</strong>​</td>
<td>有 N+1 问题,性能较差</td>
<td>性能较好,避免 N+1 问题</td>
</tr>
<tr>
<td><strong>复杂度</strong>​</td>
<td>简单,易于理解和维护</td>
<td>复杂,SQL 语句较复杂</td>
</tr>
<tr>
<td><strong>适用场景</strong>​</td>
<td>关联数据较少,延迟加载场景</td>
<td>关联数据较多,需要一次性加载所有数据</td>
</tr>
<tr>
<td><strong>内存占用</strong>​</td>
<td>较低,按需加载</td>
<td>较高,一次性加载所有数据</td>
</tr>
</tbody>
</table>
<h3 id="嵌套查询">嵌套查询</h3>
<p>在查询一个对象时,可以同时通过另一个查询语句来加载关联的另一个对象。例如,查询用户时,通过另一个查询语句来加载该用户的订单。</p>
<pre><code class="language-xml">&lt;!-- UserMapper.xml --&gt;

&lt;!-- 1. 基本的嵌套查询 --&gt;
&lt;select id="selectUserWithOrders" parameterType="Long" resultMap="userWithOrdersMap"&gt;
    SELECT * FROM users WHERE id = #{userId}
&lt;/select&gt;

&lt;resultMap id="userWithOrdersMap" type="User"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;result property="email" column="email"/&gt;
   
    &lt;!-- 嵌套查询:通过 select 属性引用另一个查询 --&gt;
    &lt;!-- 问题:会为每个用户执行一次 selectOrdersByUserId 查询 --&gt;
    &lt;collection
      property="orders"
      column="id"&lt;!-- 将主查询的 id 列值作为参数传递给嵌套查询 --&gt;
      ofType="Order"
      select="selectOrdersByUserId"/&gt;&lt;!-- 引用另一个查询语句 --&gt;
&lt;/resultMap&gt;

&lt;select id="selectOrdersByUserId" parameterType="Long" resultType="Order"&gt;
    SELECT * FROM orders WHERE user_id = #{userId}
&lt;/select&gt;

&lt;!-- 2. 一对多 + 一对一 多重嵌套 --&gt;
&lt;!-- 假设订单中还有订单项 --&gt;
&lt;select id="selectUserWithOrdersAndItems" resultMap="userWithOrdersAndItemsMap"&gt;
    SELECT * FROM users WHERE id = #{userId}
&lt;/select&gt;

&lt;resultMap id="userWithOrdersAndItemsMap" type="User"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;result property="email" column="email"/&gt;
   
    &lt;!-- 一级嵌套:用户的订单 --&gt;
    &lt;collection
      property="orders"
      column="id"
      ofType="Order"
      select="selectOrdersByUserId"/&gt;
&lt;/resultMap&gt;

&lt;!-- 订单映射,包含订单项 --&gt;
&lt;resultMap id="orderWithItemsMap" type="Order"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="orderNo" column="order_no"/&gt;
    &lt;result property="amount" column="amount"/&gt;
    &lt;result property="createTime" column="create_time"/&gt;
   
    &lt;!-- 二级嵌套:订单中的订单项 --&gt;
    &lt;collection
      property="orderItems"
      column="id"
      ofType="OrderItem"
      select="selectOrderItemsByOrderId"/&gt;
&lt;/resultMap&gt;

&lt;select id="selectOrdersByUserId" parameterType="Long" resultMap="orderWithItemsMap"&gt;
    SELECT * FROM orders WHERE user_id = #{userId}
&lt;/select&gt;

&lt;select id="selectOrderItemsByOrderId" parameterType="Long" resultType="OrderItem"&gt;
    SELECT * FROM order_items WHERE order_id = #{orderId}
&lt;/select&gt;
</code></pre>
<p>嵌套查询可能引起N+1问题:因为当我们查询一个列表时,对于列表中的每一条记录,都会执行一次额外的查询来加载关联数据。这样,如果有N条记录,就会执行1次主查询和N次关联查询,即N+1次查询。</p>
<h3 id="嵌套结果">嵌套结果</h3>
<p>通过一次复杂的联表查询,将结果映射到多个对象中。例如,通过一个SQL语句查询用户及其订单,然后通过结果映射将用户和订单的数据分别映射到用户对象和订单对象中。</p>
<pre><code class="language-xml">&lt;!-- UserMapper.xml --&gt;

&lt;!-- 嵌套结果查询:一条SQL获取所有数据 --&gt;
&lt;select id="selectUserWithOrdersNested" parameterType="Long" resultMap="userWithOrdersNestedMap"&gt;
    SELECT
      u.id AS user_id,
      u.username,
      u.email,
      o.id AS order_id,
      o.order_no,
      o.amount,
      o.create_time
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE u.id = #{userId}
&lt;/select&gt;

&lt;resultMap id="userWithOrdersNestedMap" type="User"&gt;
    &lt;id property="id" column="user_id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;result property="email" column="email"/&gt;
   
    &lt;!-- 嵌套结果映射:处理联合查询的结果集 --&gt;
    &lt;collection
      property="orders"
      ofType="Order"
      resultMap="orderResultMap"/&gt;&lt;!-- 引用订单的结果映射 --&gt;
&lt;/resultMap&gt;

&lt;resultMap id="orderResultMap" type="Order"&gt;
    &lt;id property="id" column="order_id"/&gt;
    &lt;result property="orderNo" column="order_no"/&gt;
    &lt;result property="amount" column="amount"/&gt;
    &lt;result property="createTime" column="create_time"/&gt;
&lt;/resultMap&gt;
</code></pre>
<h3 id="n1-查询问题详解">N+1 查询问题详解</h3>
<p>什么是 N+1 问题:当使用嵌套查询时,如果有 N 个主记录,每个主记录都有 M 个关联记录,那么会执行:</p>
<ul>
<li>1 条主查询</li>
<li>N 条关联查询</li>
</ul>
<p>总共执行 1 + N 条查询</p>
<p>演示案例:</p>
<pre><code class="language-java">@Test
public void testNPlusOneProblem() {
    // 查询10个用户
    List&lt;User&gt; users = userMapper.selectAllUsers();
   
    // 嵌套查询会执行:
    // 1. 查询所有用户: SELECT * FROM users; (1次)
    // 2. 为每个用户查询订单: SELECT * FROM orders WHERE user_id = ? (N次,N=10)
    // 总共执行 1 + 10 = 11 次查询!
   
    for (User user : users) {
      // 访问订单时触发额外查询
      List&lt;Order&gt; orders = user.getOrders();
      System.out.println("用户 " + user.getUsername() + " 有 " + orders.size() + " 个订单");
    }
}
</code></pre>
<p>延迟加载可以解决N+1问题:延迟加载是指在需要使用关联数据时才去加载。在MyBatis中,可以配置延迟加载,这样在查询主对象时,不会立即加载关联对象,只有当访问关联对象时才会执行额外的查询。这样,如果访问了所有关联对象,那么还是会执行N+1次查询,但如果我们只访问部分主对象的关联对象,那么就可以减少查询次数。</p>
<h4 id="延迟加载解决方案">延迟加载解决方案</h4>
<ul>
<li>配置延迟加载:mybatis-config.xml 配置</li>
</ul>
<pre><code class="language-xml">&lt;configuration&gt;
    &lt;settings&gt;
      &lt;!-- 开启延迟加载 --&gt;
      &lt;setting name="lazyLoadingEnabled" value="true"/&gt;
      
      &lt;!-- 关闭积极加载(3.4.1版本后默认为false),当开启时,任何方法的调用都会加载该对象的所有属性,否则,每个属性会按需加载 --&gt;
      &lt;setting name="aggressiveLazyLoading" value="false"/&gt;
      
      &lt;!-- 延迟加载触发方法,默认equals,clone,hashCode,toString --&gt;
      &lt;setting name="lazyLoadTriggerMethods" value=""/&gt;
      
      &lt;!-- 启用多结果集(某些数据库需要) --&gt;
      &lt;setting name="multipleResultSetsEnabled" value="true"/&gt;
    &lt;/settings&gt;
&lt;/configuration&gt;
</code></pre>
<p>application.yml 配置(Spring Boot)</p>
<pre><code class="language-yaml">mybatis:
configuration:
    lazy-loading-enabled: true
    aggressive-lazy-loading: false
</code></pre>
<ul>
<li>在映射中使用延迟加载</li>
</ul>
<pre><code class="language-xml">&lt;!-- 延迟加载配置示例 --&gt;
&lt;resultMap id="userWithLazyOrdersMap" type="User"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;result property="email" column="email"/&gt;
   
    &lt;!-- 配置延迟加载 --&gt;
    &lt;collection
      property="orders"
      column="id"
      ofType="Order"
      select="selectOrdersByUserId"
      fetchType="lazy"/&gt;&lt;!-- 设置为延迟加载 --&gt;
&lt;/resultMap&gt;

&lt;!-- 或者通过全局配置,不在每个collection单独设置 --&gt;
&lt;collection
    property="orders"
    column="id"
    ofType="Order"
    select="selectOrdersByUserId"/&gt;
</code></pre>
<p>但是,延迟加载只是将N+1次查询的时机推迟了,并没有从根本上减少查询次数。要解决N+1问题,更好的方式是使用嵌套结果(即一次联表查询)或者批量加载(MyBatis 3.4.1以上支持关联的批量加载)来减少查询次数。</p>
<h4 id="批量加载">批量加载</h4>
<pre><code class="language-xml">&lt;!-- 配置批量加载 --&gt;
&lt;settings&gt;
    &lt;!-- 开启批量加载 --&gt;
    &lt;setting name="defaultExecutorType" value="BATCH"/&gt;
   
    &lt;!-- 或者通过Mapper方法单独设置 --&gt;
    &lt;!--
    &lt;select id="selectUserWithOrders" resultMap="userWithOrdersMap"
            fetchSize="100" statementType="PREPARED"&gt;
    --&gt;
&lt;/settings&gt;
</code></pre>
<h4 id="使用嵌套结果推荐">使用嵌套结果(推荐)</h4>
<pre><code class="language-xml">&lt;!-- 使用嵌套结果替代嵌套查询 --&gt;
&lt;select id="selectUsersWithOrdersInBatch" resultMap="usersWithOrdersBatchMap"&gt;
    SELECT
      u.id AS user_id,
      u.username,
      u.email,
      o.id AS order_id,
      o.order_no,
      o.amount,
      o.create_time
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE u.id IN
    &lt;foreach collection="userIds" item="id" open="(" separator="," close=")"&gt;
      #{id}
    &lt;/foreach&gt;
    ORDER BY u.id, o.create_time DESC
&lt;/select&gt;

&lt;resultMap id="usersWithOrdersBatchMap" type="User"&gt;
    &lt;id property="id" column="user_id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;result property="email" column="email"/&gt;
   
    &lt;!-- 嵌套结果集合 --&gt;
    &lt;collection property="orders" ofType="Order"&gt;
      &lt;id property="id" column="order_id"/&gt;
      &lt;result property="orderNo" column="order_no"/&gt;
      &lt;result property="amount" column="amount"/&gt;
      &lt;result property="createTime" column="create_time"/&gt;
    &lt;/collection&gt;
&lt;/resultMap&gt;
</code></pre>
<h4 id="使用子查询--in-语句">使用子查询 + IN 语句</h4>
<pre><code class="language-xml">&lt;!-- 通过子查询减少查询次数 --&gt;
&lt;select id="selectUsersWithOrdersSmart" resultMap="userWithOrdersMap"&gt;
    SELECT * FROM users WHERE id IN (
      SELECT DISTINCT user_id FROM orders
    )
&lt;/select&gt;

&lt;select id="selectOrdersForUsers" resultType="Order"&gt;
    SELECT * FROM orders
    WHERE user_id IN
    &lt;foreach collection="userIds" item="userId" open="(" separator="," close=")"&gt;
      #{userId}
    &lt;/foreach&gt;
&lt;/select&gt;
</code></pre>


</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自在线网站:seven的菜鸟成长之路,作者:seven,转载请注明原文链接:www.seven97.top</p><br><br>
来源:https://www.cnblogs.com/sevencoding/p/19808942
頁: [1]
查看完整版本: Mybatis基础操作