前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MyBatis 集成 【Spring Boot】

MyBatis 集成 【Spring Boot】

作者头像
用户1180017
发布2018-07-04 14:20:23
8900
发布2018-07-04 14:20:23
举报
文章被收录于专栏:猿说1024猿说1024

官方说明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot

Spring Boot 集成Mybatis

在 pom.xml 中 ,使用 Spring Boot 2.0 相关依赖

代码语言:javascript
复制
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>

添加 web 和 jdbc,mybatis 依赖

代码语言:javascript
复制
<dependencies>
        <!-- Web模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </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.3.2</version>
        </dependency>

    </dependencies>
application.properties 添加相关配置
代码语言:javascript
复制
# sql config
spring.datasource.url=jdbc:mysql://192.168.158.178:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=147258369..
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#mybatis cache 配置 false xml中支持cache也无效
mybatis.configuration.cache-enabled=false

SpringBoot会自动加载<font color="#FF7f00">spring.datasource.*</font>相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

在启动类中添加对mapper包扫描<font color="#FF0000">@MapperScan</font>

代码语言:javascript
复制
/**
 * @author log.r 
 */
@SpringBootApplication
@EnableCaching
@MapperScan("com.whh.spring.boot.dao") 
public class SpringBoot2Application {

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(SpringBoot2Application.class);

        logger.info(">>>>> spring-boot 正在启动 <<<<<");
        SpringApplication.run(SpringBoot2Application.class, args);
        logger.info(">>>>> spring-boot 启动完成 <<<<<");

    }
}

或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个<font color="#FF7700">mapper</font>加个注解也挺麻烦的

Mapper 文件

可以使用 generator-plugin 生成 mapper.xml mapper.java和实体对象。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring Boot 集成Mybatis
  • application.properties 添加相关配置
  • Mapper 文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档