springboot 整合mybatis 环境搭建

本文介绍了如何在Spring Boot项目中整合MyBatis和Druid数据源,包括添加相关依赖、配置数据源、设置sqlSessionFactory、创建DAO接口以及事务管理。详细步骤帮助开发者快速搭建Spring Boot、MyBatis和Druid的集成环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、引入依赖

        spring相关依赖:spring-boot-starter-web   

        mysql 驱动 druid 数据源

        mybatis相关依赖:mybatis-spring-boot-starter

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<!--    druid    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.4</version>
        </dependency>
<!--        mysql  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

2、书写配置(步骤):

        2.1 、开启注解扫描  (省略)

                @SpringBootApplication  @ComponentScan   

        2.2、 创建数据源:指定数据源类型、数据库驱动、url、username、password

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #指定数据源
    driver-class-name: com.mysql.cj.jdbc.Driver  #mysql 8 驱动
    url: jdbc:mysql://localhost:3306/***?characterEncoding=UTF-8
    username: ***
    password: ***

        2.3、创建sqlSessionFactory

# 1、指定mapper配置文件位置

mybatis:
  mapper-locations: classpath:com/example/*/mapper/*.xml

# 2、非必须:指定实体类的包名  默认别名是类名 类名首字母小写
  type-aliases-package: com.example.*.entity

        2.4、创建dao,指定dao文件所在包:在入口类中加注释
                       或者在每个dao接口上添加@mapper注释

@SpringBootApplication
// 修饰范围:用在类上 作用:用来扫描dao接口所在包 同时将所有dao接口在工厂中创建对象
@MapperScan("com.example.*.dao")  
public class SpringBootMybatisApplication {

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

}

        2.5、创建事务管理器,开启注解式事务生效(省略)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值