wangjiedadada  

0.引入jdbc和注册驱动注解

  引入jdbc连接

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-jdbc</artifactId>
4 </dependency>

 

  引入mysql数据库驱动

1 <dependency>
2     <groupId>mysql</groupId>
3     <artifactId>mysql-connector-java</artifactId>
4     <version>5.1.47</version>
5 </dependency>

 

  整合连接池的操作

我们在引入jdbc的时候,springboot默认为我们引入了内置连接池。我们只需要配置它的一些连接信息就可以了。

1 spring:
2   datasource:
3     driver-class-name: com.mysql.jdbc.Driver
4     url: jdbc:mysql://localhost:3306/springboot_db
5     username: root
6     password: 123

 下面是jdbc版本更新之后的配置信息。

1 # 数据源配置 javax.sql.DataSource
2 spring.datasource.url = jdbc:mysql://127.0.0.1:3306/kevin?\
3   useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT
4 spring.datasource.username = root
5 spring.datasource.password = 123456
6 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

 

1.首先引入mybatis的依赖

  因为springboot官方没有提供mybatis的依赖,所以mybatis官方提供了。

1 <!--mybatis -->
2 <dependency>
3     <groupId>org.mybatis.spring.boot</groupId>
4     <artifactId>mybatis-spring-boot-starter</artifactId>
5     <version>2.0.1</version>
6 </dependency>

2.配置,mapper接口文件位置,xml文件位置,pojo实体类文件位置需要在application.yml文件当中进行指定。

  -配置每个表的xml位置信息,mybatis.mapper-locations=classpath:mappers/*Mapper.xml

  -配置每个实体类的位置:mybatis.type-aliases-package=com.kevin.mybatis.entity

  -扫描mapper接口注解:@MapperScan("com.kevin.mybatis.dao")

1 mybatis:
2   # mybatis 别名扫描
3   type-aliases-package: cn.itcast.pojo
4   # mapper.xml文件位置,如果没有映射文件,请注释掉
5   mapper-locations: classpath:mappers/**.xml

3. mapper接口的位置问题

  mapper接口的位置不能在application.yml文件当中进行配置,所以我们采用了下面两种方式。

  方式1:

     我们在每个mapper接口上面添加@Mapper注解来让spring进行扫描,然后让spring完成动态代理。

 

1 @Mapper
2 public interface UserMapper{
3 
4   void insertUser(User user);
5 }

 

  方式2:

    统一在springboot的快速启动类上面使用@Mapperscan("com.mi.demo.mappers")来扫描mappers包下的所有接口文件。

然后springboot再进行动态代理操作。

  

 1 package com.mi.demo;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.mybatis.spring.annotation.MapperScans;
 5 import org.springframework.boot.SpringApplication;
 6 import org.springframework.boot.autoconfigure.SpringBootApplication;
 7 
 8 /**
 9  * @author 王杰
10  */
11 @SpringBootApplication
12 @MapperScan("com.mi.demo.mappers")
13 public class MybatisDemo {
14     public static void main(String[] args) {
15 
16         SpringApplication.run (MybatisDemo.class,args);
17     }
18 }

 参考文章:

http://www.manongjc.com/detail/8-elzpftlhrqtmsgw.html

文章:springboot整合mybatis(推荐阅读)

地址:https://blog.csdn.net/iku5200/article/details/82856621

posted on 2021-09-08 15:36  wangjiedadada  阅读(38)  评论(0编辑  收藏  举报