Spring-整合MyBatis(基于注解)

407 阅读1分钟

前言

在经历了比较漫长的XML-Spring后,我对Spring的学习正式进入了 注解-spring阶段,在这篇文章中,想说一说用注解整合mybatis的各种操作

正文

了解相关的注解

  1. @Value:用来填充数据,参数中通常采用EL表达式,即${contents}的形式来自动注入数据

  2. @Configuration:用来标明该类为配置类,在该注解中自动包含了 @Component

  3. @PropertySource:用来导入properties文件,避免将环境写死的情况,这里需要注意的是,参数内的properties文件路径应该与配置类的路径相同,否则会识别不出来

  4. @MapperScan:用来扫描 Mapper 接口,并存储被扫描接口的一个实现类于Spring容器中,在该注解中包含了 @Import({MapperScannerRegistrar.class}),即导入MapperScannerRegistrar 类用于注册 BeanDefinition

  1. @Bean :用来产生可存储环境参数的 datasource 以及 SqlSessionFactoryBean

具体实现

  • 创建配置类 ------->创建properties文件并通过注解导入------->创建Mapper接口及其实现类, 对应xml文件, 在这个过程中需要注意xml文件与接口路径的对齐-------->使用注解扫描 Mapper 接口

    于此,配置类外部的内容就完成了,配置类内部,需要有:

  • 通过@Bean来获取dataSource,一般情况下使用DruidDataSource进行创建,需要注意的是,由于需要在内部设置mybatis的环境参数,在获取dataSource的方法的参数中应该具有这些参数,而这些参数的值应该由@Value完成自动注入 --------->通过@Bean 获取SqlSessioFactoryBean,获取该对象的方法参数中应该具有 dataSource,而获取 dataSource 的过程可以自动化,这个过程要求dataSource的获取在 SqlSessionFactoryBean 之前

    于此,配置类内部的内容也完成了,如以下代码:

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("mybatis.properties")
@MapperScan("MySQL.ComponentInters")
public class MySQLProper {

  @Bean
  public DataSource dataSource(
          @Value("${jdbc.Driver}") String driver ,
          @Value("${jdbc.url}") String url,
          @Value("${jdbc.username}")  String username,
          @Value("${jdbc.password}")  String password
  ){
      DruidDataSource dataSource=new DruidDataSource();
      dataSource.setDriverClassName(driver);
      dataSource.setUrl(url);
      dataSource.setUsername(username);
      dataSource.setPassword(password);
      return dataSource;
  }
  @Bean
  public SqlSessionFactoryBean sessionFactory(DataSource dataSource){
      SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
      sqlSessionFactoryBean.setDataSource(dataSource);
      return sqlSessionFactoryBean;
  }


}

其余细节

  • 过程中如果出现 Failed to read candidate component class: file [ ]; nested exception is org.报错

    可以尝试着在pom文件中更新spring-context插件的版本或者降低JDK版本使之兼容

  • 过程中如果出现class path resource [mybatis.properties] cannot be opened because it does not exist报错

    可以尝试着修改pom文件中的配置解决,相关代码如下:
<resources>
    <resource>
        <directory>src/main/resources/MySQL</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

总结

看起来比较容易的整合mybatis框架能玩出这么多的花样,唉呀,难受。