SpringBoot整合Mybatis-Plus(含自动配置分析)

目录

  • 1. Mybatis-Plus介绍
  • 2. 创建Mysql表和添加测试数据
  • 3. 添加pom.xml依赖
  • 4. 自动配置分析
  • 5. 代码实现
    • 5.1 User类实现
    • 5.2 指定@MapperScan扫描路径
    • 5.3 Mapper接口实现
    • 5.4 Service实现
    • 5.5 UserMapper测试

1. Mybatis-Plus介绍

Mybatis-Plus是一个Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,能提高开发效率

2. 创建Mysql表和添加测试数据

创建Mysql表,如下所示:

mysql> create table user (
    ->     id bigint(20) auto_increment not null comment '主键ID',
    ->     name varchar(30) null default null comment '姓名',
    ->     age int(11) null default null comment '年龄',
    ->     email varchar(50) null default null comment '邮箱',
    ->     primary key (id)
    -> );
Query OK, 0 rows affected, 2 warnings (0.01 sec)

mysql>

添加测试数据,如下所示:

mysql> insert into user (id, name, age, email) values
    -> (1, 'Jone', 18, '[email protected]'),
    -> (2, 'Jack', 20, '[email protected]'),
    -> (3, 'Tom', 28, '[email protected]'),
    -> (4, 'Sandy', 21, '[email protected]'),
    -> (5, 'Billie', 24, '[email protected]');
Query OK, 5 rows affected (0.04 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql>

3. 添加pom.xml依赖

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.2
        

引入了mybatis-plus-boot-starter,就不用引入mybatis-spring-boot-starter依赖了,因为所有功能都能实现

可以看到自动添加了mybatis、mybatis-spring、spring-boot-starter-jdbc依赖
SpringBoot整合Mybatis-Plus(含自动配置分析)_第1张图片

4. 自动配置分析

查看mybatis-plus-boot-starter-3.5.2.jar的META-INF\spring.factories,可以看到给我们自动配置了IdentifierGeneratorAutoConfiguration、MybatisPlusLanguageDriverAutoConfiguration、MybatisPlusAutoConfiguration

# Auto Configure
org.springframework.boot.env.EnvironmentPostProcessor=\
  com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.baomidou.mybatisplus.autoconfigure.IdentifierGeneratorAutoConfiguration,\
  com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
  com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration

现在我们重点来看MybatisPlusAutoConfiguration类,可以看到:

  • 当IOC容器中只有一个DataSource才生效
  • 绑定了MybatisPlusProperties配置类
  • 向IOC容器添加了SqlSessionFactory,并且SqlSessionFactory设置了dataSource
  • 向IOC容器添加了SqlSessionTemplate,里面就有SqlSession,就可以对数据库进行crud操作
  • 向IOC容器添加了AutoConfiguredMapperScannerRegistrar,会扫描配置文件指定的位置,将标注了@Mapper的接口添加到IOC容器;也可以通过@MapperScan注解扫描指定目录下的所有接口。这些接口是操作Mybatis-plus的接口
package com.baomidou.mybatisplus.autoconfigure;
......省略部分......
@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisPlusProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusAutoConfiguration implements InitializingBean {
......省略部分......
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        ......省略部分......
    }
......省略部分......
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        ExecutorType executorType = this.properties.getExecutorType();
        return executorType != null ? new SqlSessionTemplate(sqlSessionFactory, executorType) : new SqlSessionTemplate(sqlSessionFactory);
    }
......省略部分......
    public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
......省略部分......
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            if (!AutoConfigurationPackages.has(this.beanFactory)) {
                MybatisPlusAutoConfiguration.logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
            } else {
                MybatisPlusAutoConfiguration.logger.debug("Searching for mappers annotated with @Mapper");
            ......省略部分......
            }
            ......省略部分......
        }
    ......省略部分......
    }
......省略部分......
}

查看MybatisPlusProperties配置类,如下所示:

  • Mybatis Plus的配置由mybatis-plus开头的配置进行配置的
  • 指定了mapper.xml的path默认值:classpath*:/mapper/**/*.xml。该路径下的所有xml文件都是sql映射文件。可以通过参数mybatis-plus.mapper-locations进行配置
  • 同时集成了很多Mybatis的配置参数
......省略部分......
@ConfigurationProperties(
    prefix = "mybatis-plus"
)
public class MybatisPlusProperties {
......省略部分......
private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};
......省略部分......
    private Properties configurationProperties;
    @NestedConfigurationProperty
    private MybatisConfiguration configuration;
......省略部分......
}

5. 代码实现

5.1 User类实现

说明如下:

  • 类名默认和表名对应,如类User对应表user。可以通过@TableName指定表名
  • 字段需要一一对应,User类多余的字段用@TableField(exist = false)注解标识。如下所示:
  • 属性名如果是驼峰命名,会自动转换成下滑线和表的字段对应
package com.hh.springboottest.myController;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
@Data
public class User {
    // 以下不是数据库表对应字段
    @TableField(exist = false)
    private Integer noUseField1;
    @TableField(exist = false)
    private String noUseField2;

    //以卜是数据库表对应字段
    @TableId(value = "id", type = IdType.AUTO)  // 需要表设置主键自增
    private Long id;
    
    private String name;
    private Integer age;
    private String email;

}

5.2 指定@MapperScan扫描路径

向SpringBoot启动类,添加@MapperScan注解,指定Mapper接口的全路径位置。如下所示:

package com.hh.springboottest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.hh.springboottest.mapper")
@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);

    }
}

5.3 Mapper接口实现

UserMapper继承了BaseMapper接口

package com.hh.springboottest.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hh.springboottest.myController.User;
import org.springframework.stereotype.Repository;

@Repository    // 可以不加。不加@Autowired时IDEA会提示不能注入
public interface UserMapper extends BaseMapper {
}

BaseMapper接口实现了很多操作数据库的默认方法,所以很多方法不用我们自己实现了。如下所示:
SpringBoot整合Mybatis-Plus(含自动配置分析)_第2张图片

5.4 Service实现

UserService接口继承了Iservice接口,IService接口有很多方法。如下所示:

package com.hh.springboottest.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.hh.springboottest.myController.User;

public interface UserService extends IService {
}

UserServiceImpl实现类继承了ServiceImpl,并且指定了UserMapper和User类,这样UserServiceImpl就拥有了UserMapper的方法了。如下所示:

package com.hh.springboottest.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.springboottest.mapper.UserMapper;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl implements UserService {

}

5.5 UserMapper测试

对表数据进行其他的crud操作

package com.hh.springboottest;

import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@Slf4j
@SpringBootTest
public class MyApplicationTest {

    @Autowired
    UserService userService;

    @Test
    public void dataOperateTest() {
       
        User user = userService.getById(1L);
        List users1 = userService.list();
     
        boolean isDeleted = userService.removeById(1L);
        log.info("删除数据:{}", isDeleted ? "成功" : "失败");

    }
}

运行测试程序,结果如下:

......省略部分......
2022-11-19 21:41:40.432  INFO 4244 --- [           main] com.hh.springboottest.MyApplicationTest  : 删除数据:成功
2022-11-19 21:41:40.450  INFO 4244 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closing ...
2022-11-19 21:41:40.454  INFO 4244 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} closed

你可能感兴趣的:(#,SpringBoot,spring,boot,mybatis,mybatis,plus,自动配置分析,springboot)