Spring Boot + mybatis 开发

近期项目使用springboot框架开发,学习实践的过程中,把总结的一些内容分享出来,和正在使用的童鞋一起学习。


Spring Boot 集成MyBatis有两种方式,一种简单的方式就是使用MyBatis官方提供的:

mybatis-spring-boot-starter

另外一种方式就是使用:
mybatis-spring


第一种方式暂时没实践,第二种方式需要自己写一些代码,但是可以很方便的控制MyBatis的各项配置,下面说明第二种方式的过程。

1、 pom.xml里面配置依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring-version}</version>
</dependency>


2、 创建 mybatis 的配置类:
@Configuration
@EnableTransactionManagement
public class MyBatisConfiguration implements TransactionManagementConfigurer{
@Autowired
    DataSource dataSource;
    
@Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    
@Bean
public SqlSessionFactory sqlSessionFactory(){
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.aa.model");  //指定mybatis的模型层
SqlSessionFactory sqlFactory = null;

//添加XML目录
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:com/aa/mapper/*.xml"));
sqlFactory = bean.getObject();
} catch (IOException e) {
log.error("fail", e);
}catch (Exception e) {
log.error("fail", e);
}
return sqlFactory;
}


@Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
注意: 该类主要用于spring容器创建 SqlSessionFactory 和 SqlSessionTemplate
1)EnableTransactionManagement注解用来支持事务,关于事务控制,后续再具体讲。
2)dataSource注入的信息来自 application.properties配置的数据库相关信息,比如url,username等
3)mybatis涉及很多.xml文件,getResources支持通配


3、 mybatis涉及很多 Mapper接口,需创建这些接口的扫描类 MapperScannerConfigurer
@Configuration
@AutoConfigureAfter(MyBatisConfiguration.class)
public class MyBatisMapperScannerConfig {
@Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.aa.mapper"); //指定mybatis的mapper接口
        return mapperScannerConfigurer;
    }
}
1)必须配置AutoConfigureAfter注解,否则报错,作用: 声明在 MyBatisConfiguration 后执行


到此,springboot集成mybatis的代码结构大致完成。至于mybatis的模型层、mapper类、.xml文件等,可通过官方的插件自动生成。
关于mybatis 开发的一些细节问题,后续再另贴。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值