在Spring Boot中整合MyBatis

第1步:添加依赖:
在pom.xml文件中添加MyBatis和MySQL JDBC驱动的依赖。如果你使用的是Maven,配置如下:

   <dependencies>
       
       <dependency>
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-starter-data-jdbcartifactId>
       dependency>

       
       <dependency>
           <groupId>org.mybatis.spring.bootgroupId>
           <artifactId>mybatis-spring-boot-starterartifactId>
           <version>2.2.0version> 
       dependency>

       
       <dependency>
           <groupId>mysqlgroupId>
           <artifactId>mysql-connector-javaartifactId>
           <scope>runtimescope>
       dependency>
   dependencies>

第2步:配置数据源 DataSource:
在application.properties或application.yml文件中配置数据库连接信息:

   spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
   spring.datasource.username=root
   spring.datasource.password=mypassword
   spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

第3步:(可选)配置MyBatis全局配置文件:
如果你需要自定义MyBatis的全局配置,可以创建一个mybatis-config.xml并将其放在类路径下,然后在Spring Boot配置中指定该文件的位置:

   mybatis.config-location=classpath:mybatis-config.xml

第4步:编写实体类(POJOs):

第5步:编写Mapper接口及映射文件:
创建一个StudentsMapper.java接口,并声明对应的方法。
创建一个StudentsMapper.xml 文件放在src/main/resources/mapper/目录下。

第6步:在SpringBoot主类上或者单独的配置类上使用@MapperScan注解来自动扫描并注入Mapper接口。
主类

   @SpringBootApplication
   @MapperScan("com.example.myapp.mapper") // 替换为你的Mapper接口所在的包名
   public class MyAppApplication {
       public static void main(String[] args) {
           SpringApplication.run(MyAppApplication.class, args);
       }
   }

单独的配置类

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan(basePackages = "com.example.myapp.mapper") // 指定Mapper接口所在的包名
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource; // 注入数据源

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        // 如果有全局配置文件或映射文件路径需要指定,可以添加如下配置
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

        // 添加自定义属性等
        Properties properties = new Properties();
        properties.setProperty("mybatis.configuration.mapUnderscoreToCamelCase", "true");
        factoryBean.setConfigurationProperties(properties);

        return factoryBean.getObject();
    }

    // 可选:配置事务管理器
    // @Bean
    // public PlatformTransactionManager transactionManager(SqlSessionFactory sqlSessionFactory) {
    //     return new SqlSessionFactoryTransactionManager(sqlSessionFactory);
    // }
}

@MapperScan注解则会告诉Spring去com.example.myapp.mapper这个包及其子包下查找所有带有@Mapper注解的接口,并将它们注册为Spring Bean

必须要加 @Mapper 吗?
不是绝对必要,但是,为了更好的可读性和明确性,以及在代码重构时减少错误的可能性,强烈建议在所有的Mapper接口上都使用@Mapper注解。此外,在一些情况下,如单元测试中直接实例化Mapper接口时,@Mapper注解是必须的,因为它可以让Spring通过注解处理器自动处理依赖注入。

如果不使用@Mapper注解,要满足如下2个条件
1、 需要确保不带@Mapper注解的Mapper接口位于@MapperScan指定的包及其子包下。
例如,如果@MapperScan(basePackages = "com.example.project.mapper"),那么所有的非注解式Mapper接口必须在这个包或者其子包内,如com.example.project.mapper.StudentMapper

2、MyBatis会根据接口的全限定类名来查找对应的XML映射文件。
例如,如果你有一个名为com.example.project.mapper.StudentMapper的Mapper接口,那么其对应的XML映射文件应该如下:

<mapper namespace="com.example.project.mapper.StudentMapper">
    
    <select id="selectStudentById" resultType="com.example.project.entity.Student">
        SELECT * FROM students WHERE id = #{id}
    select>
    
    
mapper>

在这个例子中,namespace属性值为com.example.project.mapper.StudentMapper,与Java接口的全限定类名完全一致。通过这种方式,MyBatis能够正确地将XML中的SQL语句结果映射与Mapper接口的方法对应起来。即使在不使用@Mapper注解的情况下,只要保证接口名称XML映射文件的命名以及namespace属性的设置遵循上述规则,MyBatis也能正确识别并处理这些接口方法。

你可能感兴趣的:(框架,SpringBoot,spring,boot,mybatis,后端)