为了账号安全,请及时绑定邮箱和手机立即绑定

Mybatis持久层框架教程:从入门到实践

标签:
Java SSM 数据库
概述

Mybatis是一款优秀的持久层框架,它简化了Java程序员操作数据库的过程。本文将详细介绍Mybatis的使用方法,从框架的基本概念到高级特性,再到与Spring的集成。Mybatis持久层框架教程将帮助读者全面掌握Mybatis的各项功能。

Mybatis持久层框架教程:从入门到实践
Mybatis简介

Mybatis是什么

MyBatis 是一款优秀的持久层框架,它可以简化 Java 程序员的操作数据库的过程。它通过 XML 或注解的方式将 Java 对象与数据库表字段进行映射。MyBatis 使用自定义的 SQL、存储过程以及高级映射进行数据持久化。它使用简单的 API,将 Java 对象与数据库记录进行映射,从而大大减少了数据库访问的复杂性。

Mybatis的优势与应用场景

  1. 灵活的SQL支持:MyBatis 支持自定义 SQL 语句,可以针对具体业务需求编写优化的 SQL 语句,提高数据库访问性能。
  2. 强大的映射能力:MyBatis 提供了丰富的映射规则,可以将 Java 对象与数据库表字段进行灵活的映射。
  3. 低侵入性:MyBatis 不强制要求项目结构或编程风格,可以非常容易地融入到现有的项目中。
  4. 支持多种数据库:MyBatis 支持多种数据库,包括 MySQL、Oracle、SQL Server 等。
  5. 易扩展:MyBatis 支持插件系统,可以方便地扩展其功能。

Mybatis的下载与环境配置

下载Mybatis

下载 MyBatis 可以访问其官网或通过 Maven 依赖管理来引入。这里以 Maven 依赖为例:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
</dependencies>

环境配置

  1. 数据库连接配置

    创建一个 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/mydatabase" />
                   <property name="username" value="root" />
                   <property name="password" value="password" />
               </dataSource>
           </environment>
       </environments>
       <mappers>
           <mapper resource="com/example/mapper/UserMapper.xml" />
       </mappers>
    </configuration>
  2. 数据库表结构

    创建一个简单的用户表 user

    CREATE TABLE `user` (
       `id` INT(11) NOT NULL AUTO_INCREMENT,
       `username` VARCHAR(255) DEFAULT NULL,
       `password` VARCHAR(255) DEFAULT NULL,
       PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
  3. Mybatis核心配置

    创建 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="selectUserById" resultType="com.example.model.User">
           SELECT * FROM user WHERE id = #{id}
       </select>
    </mapper>
  4. Java 类与表映射

    创建映射类 User.java

    package com.example.model;
    
    public class User {
       private int id;
       private String username;
       private String password;
    
       // 构造函数、getters 和 setters 方法
    }
  5. Java 接口定义

    创建接口 UserMapper.java

    package com.example.mapper;
    
    import com.example.model.User;
    
    public interface UserMapper {
       User selectUserById(int id);
    }
  6. Mybatis 工厂初始化

    在 Java 代码中初始化 Mybatis 工厂并获取 SqlSession:

    package com.example;
    
    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.InputStream;
    
    public class MybatisDemo {
       public static void main(String[] args) throws Exception {
           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
           try (SqlSession session = sqlSessionFactory.openSession()) {
               UserMapper mapper = session.getMapper(UserMapper.class);
               User user = mapper.selectUserById(1);
               System.out.println(user);
           }
       }
    }
Mybatis的核心概念

SqlSessionFactory和SqlSession

  1. SqlSessionFactory

    SqlSessionFactory 是 MyBatis 中非常重要的一个对象,它是线程不安全的。SqlSessionFactory 可以用来创建 SqlSession,它是线程安全的。

  2. SqlSession

    SqlSession 是 MyBatis 中最核心的对象之一,它是一个线程不安全的对象。在 SqlSession 中包含了所有的数据库操作方法,例如增删改查等。

创建SqlSessionFactory和SqlSession

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();

Mapper接口和Mapper配置文件

  1. Mapper接口

    Mapper 接口是一个 Java 接口,通常对应数据库中的一个表。它定义了与数据库交互的方法,这些方法对应于 SQL 语句。

  2. Mapper配置文件

    Mapper 配置文件 (UserMapper.xml) 是一个 XML 文件,它定义了 SQL 语句和对应的 Java 方法。它通常放在 src/main/resources 目录下。

示例代码

创建 UserMapper.java 接口:

package com.example.mapper;

import com.example.model.User;

public interface UserMapper {
    User selectUserById(int id);
}

创建 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="selectUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

{}和${}的区别及使用场景

  • #{}

    #{} 用于预编译 SQL 语句中的占位符,MyBatis 会将其转换为实际的参数。这种方式可以防止 SQL 注入,提高安全性。例如:

    <select id="selectUserById" resultType="com.example.model.User">
      SELECT * FROM user WHERE id = #{id}
    </select>
  • ${}

    ${} 用于直接将参数值替换到 SQL 语句中,这种方式存在 SQL 注入的风险,但可以在某些特殊场景下使用,例如动态 SQL 语句。例如:

    <select id="selectUserById" resultType="com.example.model.User">
      SELECT * FROM user WHERE id = ${id}
    </select>

ResultMap的基本概念和使用

ResultMap 用于定义结果集与 Java 对象的映射关系。它包括字段映射、嵌套结果映射、选择性结果映射等。

示例代码

定义 UserMapper.xml 中的 ResultMap:

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="userMap" type="com.example.model.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    </resultMap>

    <select id="selectUserById" resultMap="userMap">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>
Mybatis的基本使用

CRUD操作

CRUD 是 Create (创建)、Read (读取)、Update (更新)、Delete (删除) 的缩写。MyBatis 提供了丰富的 SQL 操作来实现 CRUD 操作。

示例代码

创建 UserMapper.java 接口:

package com.example.mapper;

import com.example.model.User;

import java.util.List;

public interface UserMapper {
    User selectUserById(int id);
    List<User> selectAllUsers();
    void insertUser(User user);
    void updateUser(User user);
    void deleteUser(int id);
}

创建 UserMapper.xml 配置文件:

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="userMap" type="com.example.model.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    </resultMap>

    <select id="selectUserById" resultMap="userMap">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <select id="selectAllUsers" resultMap="userMap">
        SELECT * FROM user
    </select>

    <insert id="insertUser" parameterType="com.example.model.User">
        INSERT INTO user (username, password)
        VALUES (#{username}, #{password})
    </insert>

    <update id="updateUser" parameterType="com.example.model.User">
        UPDATE user
        SET username = #{username}, password = #{password}
        WHERE id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>

Java代码示例

package com.example;

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.InputStream;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 创建
        User user = new User();
        user.setUsername("John");
        user.setPassword("password");
        mapper.insertUser(user);
        sqlSession.commit();

        // 查询
        User userById = mapper.selectUserById(1);
        System.out.println(userById);

        // 修改
        user.setPassword("newPassword");
        mapper.updateUser(user);
        sqlSession.commit();

        // 查询所有
        List<User> allUsers = mapper.selectAllUsers();
        System.out.println(allUsers);

        // 删除
        mapper.deleteUser(1);
        sqlSession.commit();
    }
}

参数与结果映射

MyBatis 提供了丰富的参数和结果映射功能,可以灵活地处理 SQL 语句中的参数和结果。

示例代码

创建 UserMapper.java 接口:

package com.example.mapper;

import com.example.model.User;

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

public interface UserMapper {
    List<User> selectUsersByCondition(Map<String, Object> params);
}

创建 UserMapper.xml 配置文件:

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="userMap" type="com.example.model.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    </resultMap>

    <select id="selectUsersByCondition" parameterType="map" resultMap="userMap">
        SELECT * FROM user WHERE username = #{username} AND password = #{password}
    </select>
</mapper>

Java代码示例

package com.example;

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.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> params = new HashMap<>();
        params.put("username", "John");
        params.put("password", "password");

        List<User> users = mapper.selectUsersByCondition(params);
        System.out.println(users);
    }
}

批量操作和事务处理

批量操作

MyBatis 支持批量操作,可以使用 batchflush 方法来实现批量插入、更新和删除操作。

示例代码

创建 UserMapper.java 接口:

package com.example.mapper;

import com.example.model.User;

import java.util.List;

public interface UserMapper {
    void batchInsertUsers(List<User> users);
}

创建 UserMapper.xml 配置文件:

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="userMap" type="com.example.model.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    </resultMap>

    <insert id="batchInsertUsers" parameterType="java.util.List">
        INSERT INTO user (username, password)
        VALUES (#{username}, #{password})
    </insert>
</mapper>

Java代码示例

package com.example;

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.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> users = new ArrayList<>();
        users.add(new User("John", "password"));
        users.add(new User("Jane", "password"));
        mapper.batchInsertUsers(users);
        sqlSession.commit();
    }
}

事务处理

MyBatis 支持事务处理,可以通过 SqlSessioncommit()rollback() 方法来控制事务的提交和回滚。

示例代码

package com.example;

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.InputStream;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        try {
            User user = new User("John", "password");
            mapper.insertUser(user);
            sqlSession.commit();

            // 假设这里发生了异常
            int result = 1 / 0;

            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }
}
动态SQL的应用

动态 SQL 是 MyBatis 中非常强大的特性之一,它允许我们根据条件动态生成 SQL 语句。MyBatis 提供了许多标签来实现动态 SQL,例如 ifchoosewhereforeachset 等。

if标签

if 标签用于条件判断,如果条件为真,则包含的内容会被包含在生成的 SQL 语句中。

示例代码

<select id="selectUsersByCondition" parameterType="map" resultType="com.example.model.User">
    SELECT * FROM user WHERE
    <if test="username != null">username = #{username} AND </if>
    <if test="password != null">password = #{password} AND </if>
    1 = 1
</select>

Java代码示例

package com.example;

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.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> params = new HashMap<>();
        params.put("username", "John");
        params.put("password", "password");

        List<User> users = mapper.selectUsersByCondition(params);
        System.out.println(users);
    }
}

choose标签

choose 标签用于实现多条件判断,类似于 SQL 中的 CASE WHEN 语句。它会根据第一个满足条件的条件执行对应的 SQL 语句。

示例代码

<select id="selectUsersByCondition" parameterType="map" resultType="com.example.model.User">
    SELECT * FROM user WHERE
    <choose>
        <when test="username != null">username = #{username} AND </when>
        <when test="password != null">password = #{password} AND </when>
    </choose>
    1 = 1
</select>

Java代码示例

package com.example;

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.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> params = new HashMap<>();
        params.put("username", "John");
        params.put("password", "password");

        List<User> users = mapper.selectUsersByCondition(params);
        System.out.println(users);
    }
}

where标签

where 标签用于简化 WHERE 子句的生成,当第一个条件为真时,会自动去掉多余的 ANDOR

示例代码

<select id="selectUsersByCondition" parameterType="map" resultType="com.example.model.User">
    SELECT * FROM user
    <where>
        <if test="username != null">username = #{username} AND </if>
        <if test="password != null">password = #{password} AND </if>
        1 = 1
    </where>
</select>

Java代码示例

package com.example;

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.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> params = new HashMap<>();
        params.put("username", "John");
        params.put("password", "password");

        List<User> users = mapper.selectUsersByCondition(params);
        System.out.println(users);
    }
}

foreach标签

foreach 标签用于循环遍历集合或数组,生成 IN 子句等。

示例代码

<update id="updateUsersByIds" parameterType="map">
    UPDATE user
    SET username = #{username}, password = #{password}
    WHERE id IN
    <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
        #{item}
    </foreach>
</update>

Java代码示例

package com.example;

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.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> params = new HashMap<>();
        params.put("username", "John");
        params.put("password", "password");
        params.put("ids", new int[]{1, 2, 3});

        mapper.updateUsersByIds(params);
        sqlSession.commit();
    }
}

set标签

set 标签用于生成 UPDATE 语句中的 SET 子句,它可以自动过滤掉值为空的参数。

示例代码

<update id="updateUser" parameterType="com.example.model.User">
    UPDATE user
    <set>
        <if test="username != null">username = #{username}, </if>
        <if test="password != null">password = #{password}, </if>
    </set>
    WHERE id = #{id}
</update>

Java代码示例

package com.example;

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.InputStream;

public class MybatisDemo {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setUsername("John");
        user.setPassword("password");
        user.setId(1);

        mapper.updateUser(user);
        sqlSession.commit();
    }
}
Mybatis的高级特性

结果集的延迟加载

MyBatis 支持延迟加载,可以在需要时动态加载关联对象,从而提高性能。

示例代码

<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="userMap" type="com.example.model.User" lazyLoading="true">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
    </resultMap>

    <select id="selectUserById" resultMap="userMap">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

一级和二级缓存

MyBatis 支持一级缓存和二级缓存,可以提高查询性能。

示例代码

一级缓存:SqlSession 级别的缓存。

<configuration>
    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>
</configuration>

二级缓存:Mapper 级别的缓存。

<mapper namespace="com.example.mapper.UserMapper">
    <cache />
    <select id="selectAllUsers" resultType="com.example.model.User">
        SELECT * FROM user
    </select>
</mapper>

插件开发与拦截器

MyBatis 支持插件开发,可以通过拦截器来增强 MyBatis 的功能。

示例代码

package com.example.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
<configuration>
    <plugins>
        <plugin interceptor="com.example.plugin.MyPlugin">
            <property name="property" value="value" />
        </plugin>
    </plugins>
</configuration>
Mybatis与Spring集成

Mybatis与Spring整合的基本步骤

  1. 添加依赖

    pom.xml 中添加 MyBatis 和 Spring 的依赖。

    <dependencies>
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.6</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.3.10</version>
       </dependency>
       <dependency>
           <groupId>org.mybatis.spring</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>2.0.6</version>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.23</version>
       </dependency>
    </dependencies>
  2. 配置数据源

    applicationContext.xml 中配置数据源。

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
       <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
       <property name="url" value="jdbc:mysql://localhost:3306/mydatabase" />
       <property name="username" value="root" />
       <property name="password" value="password" />
    </bean>
  3. 配置SqlSessionFactory

    applicationContext.xml 中配置 SqlSessionFactory

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
  4. 配置Mapper扫描

    applicationContext.xml 中配置 Mapper 扫描。

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.example.mapper" />
    </bean>

Mybatis-Spring的事务管理

MyBatis-Spring 提供了 TransactionTemplatePlatformTransactionManager 支持事务管理。

示例代码

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

Java代码示例

package com.example.service;

import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public void createUser(User user) {
        userMapper.insertUser(user);
    }
}

Mybatis-Spring的Mapper接口开发

MyBatis-Spring 支持通过 @Mapper 注解来定义 Mapper 接口。

示例代码

package com.example.mapper;

import com.example.model.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    User selectUserById(int id);
    void insertUser(User user);
}

Java代码示例


package com.example.service;

import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUserById(int id) {
        return userMapper.selectUserById(id);
    }

    public void createUser(User user) {
        userMapper.insertUser(user);
    }
}
``

以上是 MyBatis 框架从入门到实践的详细教程,涵盖了从基础概念到高级特性的各个方面。希望通过本教程,读者能够对 MyBatis 有一个全面而深入的理解,并能熟练地使用 MyBatis 进行数据库操作。如果有更多需求或疑问,可以参考 MyBatis 的官方文档或查阅更多相关资料。
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消