Mybatis笔记

Mybatis笔记

一. MyBatis配置

1. 集成Mybatis

1.1. 初始化数据库

//创建数据库login_demo
CREATE DATABASE login_demo;
USE login_demo;

//建表user
CREATE TABLE user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL
);

1.2. 引入依赖

Mybatis依赖:

org.mybatis:mybatis:3.5.11

1.3. Mybatis核心配置文件mybatis-config.xml

配置不同环境连接的数据库

mapper配置是扫描后续的Mapper.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核心配置文件-->
<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/login_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--mapper文件扫描路径-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

1.4. 编写MyBatis工具类

package com.daimalu.utils;

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;

//sqlSessionFactory -->sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    //使用mybatis第一步,获取sqlSessionFactory对象
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了sqlSessionFactory,顾名思义,我们就可以从中获得sqlSession的实例了
    //sqlSession 完全包含了面向数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

1.5. 创建实体类

实体类为数据库表结构的映射

public class User {
    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

1.6. 编写Mapper接口类

Dao层用于声明对应表的操作方法

Mapper接口就是Dao层,根据命名习惯选择即可

public interface UserDao {
    List<User> findAll();
    User findById(Integer id);
    User findByName(String name);
}

1.7. 编写Mapper.xml配置文件

在对应xml文件内配置Mapper接口中声明方法的sql语句

确定Mapper,User,Dao层的联系。

<?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.login_demo.dao.UserDao">
    <select id="findAll" resultType="com.example.login_demo.entity.User">
        SELECT * FROM user
    </select>

    <select id="findById" parameterType="int" resultType="com.example.login_demo.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <select id="findByName" parameterType="String" resultType="com.example.login_demo.entity.User">
        SELECT * FROM user WHERE name = #{name}
    </select>
</mapper>

1.8. 编写测试类(可选)


package com.daimalu.dao;

import com.daimalu.pojo.User;
import com.daimalu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    //第一步:获得sqlSession对象
    SqlSession sqlSession;
    @Test
    public void test(){
        try {

            sqlSession = MybatisUtils.getSqlSession();
            //方式一:getMapper
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            //关闭sqlSession
            sqlSession.close();
        }

    }
}


2. SpringBoot简化Mybatis配置

2.1. 引入依赖改动

Mybatis依赖(springBoot特化):

org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3

2.2. 核心配置文件改动

mybatis-config.xml中配置在application.yml中进行

配置会由Spring Boot自动管理

spring:
  application:
    name: login-demo
    
  datasource:
    url: jdbc:mysql://localhost:3306/login_demo
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations:
  - classpath:mappers/*.xml

2.3. 工具类改动

Spring Boot会默认自动配置MyBatis工具类,无特殊要求不再需要手动配置

2.4. Mapper接口类改动

使用@Mapper注解,让 MyBatis 能自动扫描并识别该接口,生成代理对象,实现数据库操作。

@Mapper
public interface UserDao {
    List<User> findAll();
    User findById(Integer id);
    User findByName(String name);
}

二. MyBatis Generator 配置(待补充)

如果你不想手动配置entity,mapper,且你没有特殊的需求,不妨不妨使用MyBatis Generator,这个依赖可以根据数据库中表自动生成对应的entity,mapper等配置。

1. generatorConfig.xml

三. Mybatis-plus 配置

1. 配置文件

1.1. 可配置内容

配置内容有四部分,具体可配置选项可参考官方文档:https://baomidou.com/reference/#dbconfig

  • Base 基本路径配置
  • Configuration mybatis配置
  • GlobalConfig 全局策略配置
    • DbConfig 数据库配置

1.2. SpringBoot配置

可以通过 application.yml 或 application.properties 文件来配置 MyBatis-Plus。

mybatis-plus:
    # config-location: classpath:/mybatis-config.xml 
    mapper-locations: classpath:/mapper/**.xml

    configuration:
        map-underscore-to-camel-case: true 

    global-config: 
        db-config:
            id-type: auto

1.3. Spring MVC 配置

可以通过 XML 配置文件来配置 MyBatis-Plus。

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="classpath*:mapper/**/*.xml"/>
    <property name="typeAliasesPackage" value="com.your.domain"/>
    <!-- 其他配置 -->
</bean>

2. 代码生成器

提示:常规的手动配置依旧生效,可参考Mybatis的配置

既然使用Mybatis-Plus,那多少要用一下这个功能的。
官方文档:MyBatis-Plus Guides

2.1. 依赖

com.baomidou:mybatis-plus-generator:3.5.5
org.freemarker:freemarker

//这里说明freemarker
mybatis-plus-generator的执行需要模板引擎,默认使用的是freemarker,
不过mybatis-plus-generator中引入了模板引擎,但不进行传递,即<optional>true</optional>,
故需要显示声明模板引擎。

2.2. CodeGenerator.java

代码生成器通过执行一个main函数,在里面调用建造者构建。

这是官方的快速启动推荐:(需要自定义可查看官方文档,内容不多)

public static void main(String[] args) {
    FastAutoGenerator.create("url", "username", "password")
            .globalConfig(builder -> {
                builder.author("baomidou") // 设置作者
                        .enableSwagger() // 开启 swagger 模式
                        .outputDir("D://"); // 指定输出目录
            })
            .dataSourceConfig(builder ->
                    builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                        int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                        if (typeCode == Types.SMALLINT) {
                            // 自定义类型转换
                            return DbColumnType.INTEGER;
                        }
                        return typeRegistry.getColumnType(metaInfo);
                    })
            )
            .packageConfig(builder ->
                    builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
                            .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")) // 设置mapperXml生成路径
            )
            .strategyConfig(builder ->
                    builder.addInclude("t_simple") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_") // 设置过滤表前缀
            )
            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
            .execute();
}

报错记录

0. 不妨考虑清空缓存试试?

1. Invalid value type for attribute 'factoryBeanObjectType': java.lang.String

原因:

    mybatis-spring 旧版本的 ClassPathMapperScanner#processBeanDefinitions 方法里将 BeanClassName 赋值给 String 变量 beanClassName,并将 beanClassName 赋值给 factoryBeanObjectType。
    在Spring Boot 3.2 版本中,FactoryBeanRegistrySupport#getTypeForFactoryBeanFromAttributes方法已变更,如果 factoryBeanObjectType 不是 ResolvableType 或 Class 类型会抛出 IllegalArgumentException 异常。

解决方案:
官方 ISSUE 说明:mybatis-spring在 3.03 修复此问题

  1. org.mybatis:mybatis-spring:3.0.3 (指定mybatis-spring版本为3.0.3)
  2. com.baomidou:mybatis-plus-spring-boot3-starter:3.5.5 (内置mybatis-spring版本升级至3.0.3)

2. Failed to replace DataSource with an embedded database for tests

原因:

@MybatisPlusTest默认使用H2数据库,会尝试将数据源替换到H2,若你未引入H2数据库,自然无法找到。

解决方案:

  1. @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) (该注解可以设置自动替换为NONE,即不指定)
  2. 使用@SpringBootTest (该注解默认使用application.yaml中配置数据源)
  3. 小提示:
@MybatisPlusTest默认会进行事务回滚,@SpringBootTest不会
posted @ 2025-10-10 00:39  Insanial  阅读(7)  评论(0)    收藏  举报