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");
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容