springboot自动装配原理及如何整合mybatis-plus

SpringBoot自动装配原理与Mybatis-Plus集成实践
文章详细介绍了SpringBoot的包扫描和自动装配机制,包括@SpringBootApplication和@EnableAutoConfiguration的作用。同时,文章阐述了Mybatis-Plus的特性,如无侵入性、高性能和丰富的CRUD操作,并展示了如何在SpringBoot项目中配置数据源、引入Mybatis-Plus依赖、创建实体类和Mapper接口,以及进行分页查询和条件查询的示例代码。

1.springboot自动装配原理

        1.1springboot包扫描原理

        包扫描默认扫描主类所在的包及其子包下

        主函数在运行时会加载一个使用@SpringBootApplication标记的类。而该注解是一个复合注解,包含@EnableAutoConfiguration,这个注解开启了自动配置功能。 该注解也是一个复合注解,包含@AutoConfigurationPackage。 该注解中包含@Import({Registrar.class}),这个注解引入Registrar类。该类中存在registerBeanDefinitions,可以获取扫描的包名。

如果需要人为修改扫描包的名称则需要在主类上@ComponentScan(basepackage={"包名"})

        1.2springboot自动装配原理

        主函数在运行会执行一个使用@SpringbootApplication注解的类,该注解是一个复合注解,包含@EnableAutoConfiguration, 该注解开启自动配置功能,该注解也是一个复合注解,包含@Import() 该注解需要导入AutoConfigurationImportSelector类。 该类会加载很多自动装配类,而这些自动装配类完成相应的自动装配原理。

2.springboot整合mybatis-plus

        2.1mybatis-plus简介

        MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

        2.2mybatis-plus特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操做

        2.3如何使用mybatis-plus

        (1)导入mybatis-plus相关依赖

   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

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

      (2)配置数据源

pom文件未添加druid的依赖时数据如下配置

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///homework

pom文件中添加了druid的依赖时如下配置

<!-- druid依赖 -->
     <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
     </dependency>
​#数据源的配置
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/homework
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
spring.datasource.druid.initial-size=5

(4)创建实体类

@Data
public class Student(){
   
     private int sid;
     private String sanme;
     private int age;
     private int ccid;
}

(5)创建接口   需要继承BaseMapper

public interface StudentMapper extends BaseMapper<Student> {
    
}

(6)为接口生成代理实现类

@SpringBootApplication
@MapperScan(basePackages = "com.xwh.mapper")
public class   Springboot0411Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot0411Application.class, args);
    }

}

(7)测试

   @Autowired
    private StudentMapper studentMapper;


    @Test
    void insert(){
        Student student = new Student("liuneng", 34, 2);
        int insert = studentMapper.insert(student);
        System.out.println(insert);
    }

    @Test
    void delete(){

        int i = studentMapper.deleteById(6);
        System.out.println(i);
    }

    @Test
    void delete2(){
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(4);
        ids.add(5);
        ids.add(6);
        int i = studentMapper.deleteBatchIds(ids);
        System.out.println(i);
    }

    @Test
    void update(){
        Student student = new Student("momo", 21, 2);
        student.setSid(8);
        int i = studentMapper.updateById(student);
        System.out.println(i);
    }
    @Test
    void find1(){
        List<Student> students = studentMapper.selectList(null);
        students.forEach(System.out::println);
    }

    @Test
    void find2(){
        Student student = studentMapper.selectById(6);
        System.out.println(student);
    }

2.4查询分页时要进行mybatis-plusfenye拦截器配置

        配置类要放在主类所在bao或者其子包下

@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

2.5使用mybatis-plus完成条件查询并分页

  @Test
    public void testFind(){
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        //查询年龄大于22
        // wrapper.gt("age",22);

        wrapper.like("sname","x");
        wrapper.between("age",22,25);
        wrapper.orderByDesc("age");

        List<Student> students = studentMapper.selectList(wrapper);
        students.forEach(System.out::println
        );
    }

    @Test
    void findPage1(){
        Page<Student> page = new Page<>(1,3);
        Page<Student> studentPage1 = studentMapper.selectPage(page, null);
        System.out.println("当前页的记录"+page.getRecords());//获取当前页的记录
        System.out.println("获取总页数"+page.getPages());//获取当前页的记录
        System.out.println("获取总条数"+page.getTotal());//获取当前页的记录
    }

2.6mybatis-plus联表分页查询

        在进行联表查询时要自己手写sql语句

  <select id="findPage" resultMap="BaseResultMap">
        select <include refid="Base_Column_List"/> from student s join class c on s.ccid = c.cid
<if test="ew != null">
    <where>
        ${ew.sqlSegment}
    </where>
</if>
    </select>
   @Test
    void findPage() {

        Page<Student> page=new Page<>(1,2);
        QueryWrapper<Student> wrapper=new QueryWrapper<>();
        wrapper.gt("age",22);
        studentMapper.findPage(page,wrapper);
        System.out.println("当前页的记录"+page.getRecords());//获取当前页的记录
        System.out.println("获取总页数"+page.getPages());//获取当前页的记录
        System.out.println("获取总条数"+page.getTotal());//获取当前页的记录

    }

### Spring Boot 3.3.7 集成 MyBatis-Plus 的教程 #### 创建项目结构 为了在Spring Boot 3.3.7中集成MyBatis-Plus,首先需要创建一个新的Spring Boot应用程序并设置好项目的初始结构。 #### 添加依赖项 在`pom.xml`文件中添加必要的Maven依赖来支持MyBatis-Plus: ```xml <dependencies> <!-- Other dependencies --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> <!-- Database driver dependency --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Optional: Lombok for concise code --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> ``` 注意替换`最新版本号`为实际使用的MyBatis-Plus版本[^4]。 #### 编写启动类 定义应用入口点,并指定要扫描的Mapper接口所在的包路径。这可以通过向带有`@SpringBootApplication`注解的应用程序主类添加`@MapperScan`注解完成: ```java package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 上述代码展示了如何通过`@MapperScan`指明映射器的位置以便自动装配Spring容器内[^2]。 #### 数据源配置 编辑`application.yml`或`application.properties`以提供数据库连接详情和其他相关属性: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ``` 此部分确保了数据源能够被正确初始化并与MySQL或其他关系型数据库建立联系。 #### 实现分页功能 为了让查询操作具备分页能力,可以在全局范围内注册一个拦截器——`PaginationInnerInterceptor`。为此需编写自定义配置类如下面所示: ```java @Configuration public class MybatisConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` 这段Java代码片段实现了对SQL执行过程中的分页逻辑的支持[^5]。 #### 测试实体和服务层 最后一步是构建领域模型(Entity)、仓库接口(Repository/Mapper),以及服务层(Service),从而形成完整的CRUD操作链路。这里不再赘述具体细节,因为这些通常遵循标准的设计模式和最佳实践原则。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值