spring boot整合mybatis

来源:互联网 发布:江苏网络电视台 编辑:程序博客网 时间:2024/05/08 04:07

Spring整合mybatis其实很简单啊。
首先是一个jar包的问题,使用maven可以很方便地配置

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-tx</artifactId></dependency><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis-spring</artifactId>    <version>1.3.0</version></dependency><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis</artifactId>    <version>3.3.1</version></dependency><dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.39</version>

这五个jar包的maven配置是必不可少的。
如果是注解方式开发mybatis,那么需要配置三个核心的bean。
第一个肯定是连接数据库的数据源。
数据源可以选很多种,我随便挑一个吧。

@Beanpublic DataSource dataSource(){    PooledDataSource dataSource = new PooledDataSource();    dataSource.setDriver("com.mysql.jdbc.Driver");    dataSource.setUrl("jdbc:mysql://localhost:3306/study");    dataSource.setUsername("root");    dataSource.setPassword("123456");    return dataSource;}

其次是SqlSessionFactoryBean,这个东西是mybatis的核心,没有这个就没法使用mybatis。

@Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {     SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();     factoryBean.setDataSource(dataSource);     return factoryBean; }

当然配置完了这两步也就够了。
但是这样配置开发的时候就麻烦了,因为mapper类不会加入到spring的容器中,所以开发要方便的话还需要配置mybatis mapper类的自动扫包。

@Beanpublic MapperScannerConfigurer scannerConfigurer(){    MapperScannerConfigurer configurer = new MapperScannerConfigurer();    configurer.setBasePackage("com.cjxnfs.springbootdemo.mapper");    return configurer;}

自动扫包还有个解决方案就是使用注解。

@MapperScan("com.cjxnfs.springbootdemo.mapper")

这个注解代替MapperScannerConfigurer的配置可以节省不少代码。
配完这三个bean,mybatis的配置就完成了。
如果说使用mybatis-spring-boot-starter,那么配置更加简单。
maven的配置就要修改了。
将mybatis-spring的依赖改成mybatis-spring-boot-starter的依赖。
就是下面的代码:

org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0

那三个bean的配置只需要保留Datasource的配置。因为SQLsessionfactory它会自动创建,但是@MapperScan扫包配置不可少。

原创粉丝点击