MyBatis 学习教程

全面的 MyBatis 和 MyBatis Plus 开发指南

目录

1. MyBatis 简介

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 几乎消除了所有的 JDBC 代码和参数的手动设置以及结果集的检索。

1.1 特点

2. 环境搭建

2.1 Maven 依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.13</version>
</dependency>

2.2 基础配置

<?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/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

3. 基础概念

3.1 核心组件

3.2 工作流程

// 获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 获取 SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
    // 执行 SQL
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    Blog blog = mapper.selectBlog(101);
}

4. XML 配置

4.1 配置文件结构

配置提示

建议将数据库配置信息放在单独的 properties 文件中,便于管理和切换环境。

5. 映射文件

5.1 基本映射

<?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.BlogMapper">
    <select id="selectBlog" resultType="Blog">
        SELECT * FROM blog WHERE id = #{id}
    </select>
</mapper>

5.2 结果映射

<resultMap id="blogResult" type="Blog">
    <id property="id" column="blog_id" />
    <result property="title" column="blog_title"/>
    <association property="author" javaType="Author">
        <id property="id" column="author_id"/>
        <result property="name" column="author_name"/>
    </association>
</resultMap>

6. 动态 SQL

6.1 常用标签

6.2 示例

<select id="findActiveBlogLike" resultType="Blog">
    SELECT * FROM blog WHERE state = 'ACTIVE'
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
</select>

7. 注解开发

7.1 基本注解

@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);

@Insert("INSERT INTO blog (title, content) VALUES (#{title}, #{content})")
int insertBlog(Blog blog);

@Update("UPDATE blog SET title = #{title} WHERE id = #{id}")
int updateBlog(Blog blog);

@Delete("DELETE FROM blog WHERE id = #{id}")
int deleteBlog(int id);

7.2 高级注解

8. 高级特性

8.1 缓存机制

8.2 插件开发

@Intercepts({
    @Signature(type = Executor.class, method = "update",
        args = {MappedStatement.class, Object.class})
})
public class ExamplePlugin implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        return invocation.proceed();
    }
}

9. MyBatis Plus

9.1 特性介绍

9.2 快速开始

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3</version>
</dependency>

@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
}

public interface UserMapper extends BaseMapper<User> {
}

9.3 条件构造器

// 查询条件构造
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
    .like("name", "张")
    .ge("age", 20)
    .orderByDesc("id");

// 更新条件构造
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper
    .set("age", 18)
    .eq("name", "张三");

9.4 分页查询

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

// 使用分页
Page<User> page = new Page<>(1, 10);
Page<User> userPage = userMapper.selectPage(page, null);

10. 最佳实践

10.1 开发建议

10.2 性能优化

注意事项

在使用 MyBatis Plus 时,建议先熟悉原生 MyBatis 的使用,这样能更好地理解和使用增强功能。