zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Mybatis注解之@Mapper和@MapperScan的使用

mybatis 注解 Mapper 使用
2023-09-14 09:04:53 时间

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

<!--myabtis-->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

1、@Mapper注解

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

优点:粒度更细

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

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

添加位置:接口类上面

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

@Mapper
public interface StudentMapper {
    
    //查询所有学生
    List<Student> selectall();
    
    //新增学生
    int addstudent(Student student);

    //删除学生
    int delstudent(Integer sid);

    //修改学生
    int updatestudent(String sname,Integer sid);
    
}

2、@MapperScan注解

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

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

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

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

@MapperScan(basePackages = {"com.study.suke.mapper"})
@SpringBootApplication
public class DemocsApplication {

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

}

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

@MapperScan(basePackages = {"com.study.suke.mapper1","com.study.suke.mapper2"})
@SpringBootApplication
public class DemocsApplication {

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

}

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

@MapperScan(basePackages {"com.study.suke*.mapper"})
@SpringBootApplication
public class DemocsApplication {

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

}