• mybatis注解之@Mapper和@MapperScan的使用


    首先,我们要使用@Mapper和@MapperScan注解的话,我们首先需要在对应的项目里面导入相关的依赖或者jar包。

    1. <dependency>
    2. <groupId>org.mybatis.spring.bootgroupId>
    3. <artifactId>mybatis-spring-boot-starterartifactId>
    4. <version>2.1.2version>
    5. dependency>

    1、@Mapper注解

    前言:从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件。

    优点:粒度更细

    缺点:直接在Mapper接口类中加@Mapper注解,需要在每一个mapper接口类中都需要添加@Mapper注解,较为繁琐

    作用:在接口类上添加了@Mapper,在编译之后会生成相应的实现类

    添加位置:接口类上面

    注意:在这个接口类里面的方法不能重载,因为他们在XML里面的ID不能一样

    1. @Mapper
    2. public interface StudentMapper {
    3. //查询所有学生
    4. List selectall();
    5. //新增学生
    6. int addstudent(Student student);
    7. //删除学生
    8. int delstudent(Integer sid);
    9. //修改学生
    10. int updatestudent(String sname,Integer sid);
    11. }

    2、@MapperScan注解

    上面刚刚讲述了@Mapper注解可以把接口要变成实现类,如果项目有几个接口,你肯定会在对应的接口上写@Mapper注解,但是如果有一百个,上千个,你还会愿意去写吗,这个时候我们就可以使用@MapperScan注解来解决我们的问题。

    作用:指定要变成实现类的接口所在的包,然后在指定包下面的所有接口在SpringBoot启动编译完成之后生成相应的实现类

    添加位置:在Springboot启动类上面添加

    (1)通过@MapperScan可以指定要扫描的Mapper接口类的包路径

    1. @MapperScan(basePackages = {"com.study.suke.mapper"})
    2. @SpringBootApplication
    3. public class DemocsApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(DemocsApplication.class, args);
    6. }
    7. }

    (2)可以使用@MapperScan注解对多个包进行扫描 

    1. @MapperScan(basePackages = {"com.study.suke.mapper1","com.study.suke.mapper2"})
    2. @SpringBootApplication
    3. public class DemocsApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(DemocsApplication.class, args);
    6. }
    7. }

    (3)这里的.*代表的是扫描study下面下面任何带有mapper文件

    1. @MapperScan(basePackages {"com.study.suke*.mapper"})
    2. @SpringBootApplication
    3. public class DemocsApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(DemocsApplication.class, args);
    6. }
    7. }
  • 相关阅读:
    postgresql源码学习(36)—— 事务日志11 - 日志归档
    你知道什么是SaaS吗?
    git使用看这一篇就够了
    nacos不同局域网如何相互调用?nacos微服务云开发,远程联调部署,内网穿透,frp部署
    springBoot整合讯飞星火认知大模型
    VR虚拟现实:VR技术如何进行原型制作
    WebStorm 2024.1.1 Mac激活码 前端开发工具集成开发环境(IDE)
    单片机实物焊接器件识别
    互联网时代下的品牌传播怎么做
    BPMN是什么
  • 原文地址:https://blog.csdn.net/qq_45037155/article/details/127951816