Spring Boot:整合Mybatis
1.导入整合需要的依赖(同时连接数据库)
<!--mybatis整合springboot依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.编写application配置文件
下面以properties文件展示,yaml文件编写差不多:
application.properties:
spring.datasource.username=#用户名
spring.datasource.password=#密码
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名)?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 整合mybatis
# 配置pojo类别名
mybatis.type-aliases-package=com.huang.pojo
# 配置mapper映射文件路径
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
3.测试是否能连接成功
package com.huang;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
@SpringBootTest
class Spring05MybatisApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() {
System.out.println(dataSource.getClass());
}
}
4.编写mapper接口
package com.huang.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
//这个注解表示这是一个Mybatis的Mapper类
@Mapper
//将这个类注册到spring中,标识这个dao层
@Repository
public interface UserMapper {
}
5.编写mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huang.mapper.UserMapper">
</mapper>