01_SpringBoot集成MyBatis

@Author Jack Wang
转载请注明出处,http://www.jianshu.com/p/8138ccd0d900

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

另外一种方式就是仍然用类似mybatis-spring的配置方式,这种方式需要自己写一些代码,但是可以很方便的控制MyBatis的各项配置。

2018.09.10 , 第一次更新

一:mybatis-spring-boot-starter方式【推荐】

1.1 创建Maven工程,搭建包结构
06.png
或者使用springboot initializer自动创建工程, http://start.spring.io/
1.2 构建环境,使用mybatis generatorConfig插件自动生成entity及mapper
generatorConfig.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <classPathEntry
        location="D:\repositories\repository_hh\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar" />
    <context id="generator-code">
    <commentGenerator>           
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->             
            <property name="suppressAllComments" value="true"/>      
         </commentGenerator>  
         
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/license_system?characterEncoding=utf8" userId="root"
            password="jacky" />
        <javaModelGenerator targetPackage="com.dream.mybatis.entity"
            targetProject="springboot-mybatis/src/main/java" />
        <sqlMapGenerator targetPackage="com.dream.mybatis.mapper"
            targetProject="springboot-mybatis/src/main/resources" />
        <javaClientGenerator targetPackage="com.dream.mybatis.dao"
            targetProject="springboot-mybatis/src/main/java" type="XMLMAPPER" />
        <table tableName="t_equipment" domainObjectName="Equipment"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_department" domainObjectName="Department"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_employee" domainObjectName="Employee"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_license" domainObjectName="License"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_project" domainObjectName="Project"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_project_detail" domainObjectName="ProjectDetail"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_project_license_asso" domainObjectName="ProjectLicenseAsso"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_user" domainObjectName="User"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
        <table tableName="t_warehouse" domainObjectName="Warehouse"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

注意mysql的jar包及数据库连接属性以及表格要与实际情况一一对应。
mybatis-generator插件在eclipse market商店搜索插件下载即可。右键generatorConfig.xml运行插件就可以自动生成。
02.png
03.png
1.3 pom添加Maven依赖,properties中添加配置
pom : 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 热部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>true</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

================================================================================

application.properties :
    spring.datasource.url=jdbc:mysql://localhost:3306/license_system
    spring.datasource.username=root
    spring.datasource.password=jacky
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml

***注意:这里mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml是配置mapper.xml的路径的。
确保路径正确,并且xml中namespace对应的Mapper接口无误,否则可能会报异常:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.dream.mybatis.dao.WarehouseMapper.insert
1.4 Springboot启动入口Application
@SpringBootApplication
@MapperScan("com.dream.mybatis.dao")
public class Application {

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

注意:这里配置的@MapperScan("xx.xx.xx")是配置Mapper接口的位置,确保位置对应正确

到这里springboot集成mybatis就已经结束了,真正需要我们进行配置的只有几点:

1. 添加maven依赖。mybatis-spring-boot-starter及mysql驱动
2. 配置application.properties中mapper.xml的位置。mybatis.mapperLocations=classpath*:com/dream/mybatis/mapper/*.xml
3. Application.java中Mapper接口的位置。@MapperScan("com.dream.mybatis.dao")

事务的支持还和平常使用一样,在Service上添加@Transactional注解即可。

@Service
@Transactional
public class WarehouseServiceImpl implements WarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;
    
    @Override
    public void insert() {
        Warehouse record = new Warehouse();
        record.setId(888L);
        record.setName("测试回滚");
        warehouseMapper.insert(record);
        int i = 1/0;
    }
}

二、mybatis-spring方式

2.1 创建Maven工程,搭建包结构
06.png
包结构与方式一一样
2.2 构建环境,使用mybatis generatorConfig插件自动生成entiry及mapper(略)
2.3 pom添加Maven依赖,properties中添加配置
1. pom中添加的依赖与方式一不同,这里是使用mybatis-spring依赖进行集成

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <!-- 热部署插件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>true</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

-------------------------------------------------------------------------------------------------

2. application.properties只需要添加springboot数据库连接的配置即可

    spring.datasource.url=jdbc:mysql://localhost:3306/license_system
    spring.datasource.username=root
    spring.datasource.password=jacky
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.4 MyBatis配置类
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
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.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import com.github.pagehelper.PageHelper;

@SpringBootConfiguration
@MapperScan({"invengo.cn.base.mapper"})
@AutoConfigureAfter(DBConfiguration.class)
public class MyBatisConfig implements TransactionManagementConfigurer {

    // Springboot根据properties自动完成配置的DataSource
    @Autowired
    private DataSource dataSource;


    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(PageHelper pageHelper) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/*.xml"));
        // sqlSessionFactoryBean.setPlugins(new Interceptor[] { pageHelper });
        return sqlSessionFactoryBean.getObject();
    }
    
    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
    
    // 分页支持
    /*@Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("dialect", "mysql"); // 配置mysql数据库的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }*/
}

注意:
1. @MapperScan("com.dream.mybatis.dao")用于扫描Mapper接口,注意路径
2. sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/*.xml"));用于配置mapper.xml的路径
3. 注释的部分为使用该方式时对PageHelper插件的支持,后面章节会使用到PageHelper插件

事务的支持还和平常使用一样,在Service上添加@Transactional注解即可。
2.5 Application启动类
@SpringBootApplication
public class PayApplication {
    private static Logger logger = Logger.getLogger(PayApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(PayApplication.class, args);
        logger.info("SpringBoot Start Success");
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容