-
首先建库建表
-
在表中写数据
-
用init创建一个springboot项目
-
在配置文件配置数据库信息
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_db?serverTimezone=UTC username: root password: a123456789 -
编写实体类
package com.hiyiin.entity; public class Book { private Integer id; private String type; private String name; private String description; //getter、setter、toString } -
dao
**注意:**写上Mapper注解表示交给SpringBoot管理并作为MyBatis的mapper类
@Mapper public interface BookDao { @Select("select * from book where id = #{id}") Book getById(Integer id); } -
进行测试
测试类
@Autowired private BookDao bookDao; @Test void contextLoads() { Book book = bookDao.getById(5); System.out.println(book); }
MyBatis和MyBatis-Plus区别
- 导入坐标不同
- 数据层实现简化
步骤:
-
与之前一样创建项目,只勾选一个mysql驱动就行
-
在pom.xml中导入如下依赖
com.baomidou mybatis-plus-boot-starter 3.5.2 -
其他的操作与整合mybatis类似,还有一个地方不同,就是它的dao只需要继承一个BaseMapper<实体类>就行了。
@Mapper public interface BookDao extends BaseMapper
{ }
**注意:**MyBatis-Plus匹配表明需要与实体类名一致,否则需要在springboot核心配置文件中配置MyBatis-Plus表名前缀或后缀。
mybatis-plus:
global-config:
db-config:
table-prefix:
整合Druid
步骤:
-
直接在mybatisplus项目中的pom.xml中加入druid的依赖
com.alibaba druid-spring-boot-starter 1.2.9 -
修改一下核心配置文件,由两种写法
-
直接在后面加个type
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_db?serverTimezone=UTC username: root password: a123456789 type: com.alibaba.druid.pool.DruidDataSource -
使用druid配置datasource
spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_db?serverTimezone=UTC username: root password: a123456789
-
-
两种方法都能用,但加type的写法并不是整合,第二种方法更为正统
SpringBoot整合第三方技术的通用方法:
- 导入对应的starter
- 根据提供的配置格式,配置非默认值对应的配置项



