SpringBooot整合Mybatis
- 创建新模块,选择Spring初始化,并配置模块基础信息
- 选择需要使用的技术集(其实就是在模块建立之后boot给你自动添加的依赖包)
- 设置数据源参数
注意在boot版本低于2.4.3(不含),Mysql驱动大于8.0是,需要在url连接串中配置时区
jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
- 创建数据库实体类
package com.itheima.domain;
import lombok.Data;
@Data
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}
- 定义数据层接口与映射配置
数据库Sql映射需要添加@Mapper被容器识别到
package com.itheima.dao;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface BookDao {
@Select("select * from tb1_book where id =#{id}")
public Book selectById(Integer id);
}
- 测试类注入dao接口,测试功能
package com.itheima;
import com.itheima.dao.BookDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot04MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
System.out.println(bookDao.selectById(1));
}
}
Springboot整合Mybatis-Plus
- 手动添加Mybatis-Plus坐标(因为SpringBoot中未收录MP坐标)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
- 定义数据层接口继承BaseMapper
@Mapper
@Repository
public interface BookDao extends BaseMapper<Book> {
}
- 其它同mybatis一致
可能会出现的错误:
结果在测试时出现错误
错误原因:未找到ssm_db数据库下的book表。这是因为MP自动将数据库中数据封装到对应实体类,但在数据库中为找到名字为book的表因此报错。
解决方式一:在配置文件中添加MP配置信息
#MP配置
mybatis-plus:
global-config:
db-config:
table-prefix: tb1_
数据库中表名为tb1_book,实体类名为book,所以需要在配置前缀tb1_
解决方式二:在实体类上添加注释@TableName
@Data
@TableName("tb1_book")
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}
设置数据库名与之对应
SpringBoot整合Druid
- 手动添加druid坐标(因为SpringBoot中未收录druid坐标)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
- 配置druid数据
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: mysql