SpringBoot系列之整合MyBatis框架
文章目录
- 一、引入MyBatis起步依赖
- 二、编写DataSource和MyBatis相关配置
- 1.在application.yml或者application.properties中编写DataSource
- 三.编写实体类
- 四、编写mapper接口
- 五、修改application.yml 新增如下配置
Springboot如何整合Mybatis框架呢?
SpringBoot整合Mybatis框架只需引入MyBatis起步依赖
一、引入MyBatis起步依赖
搭建好SpringBoot工程后,在pom.xml中引入起步依赖,以及mysql驱动(不同数据库需添加不同驱动包)
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
<scope>runtime</scope>
</dependency>
二、编写DataSource和MyBatis相关配置
1.在application.yml或者application.properties中编写DataSource
代码如下(示例):
spring:
datasource:
url: jdbc:mysql://localhost:3306/XXX?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
password: adminLp
username: root
三.编写实体类
代码如下(示例):
public class User {
int id;
String name;
int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
四、编写mapper接口
@Mapper
public interface UserDaoXml {
List<User> findAll();
}
resources下建立xml文件 UserMapper.xml
<?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="org.elp.dao.UserDaoXml">
<select id="findAll" resultType="org.elp.pojo.User">
select * from user
</select>
</mapper>
五、修改application.yml 新增如下配置
mybatis:
mapper-locations: classpath:mapper/*
最后启动测试类即可