一、springboot整合MyBatis
1.引入MySQL依赖
<!--spring整合mybatis-->
<!-- mybatis-springboot-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
mysql-connector-java – 版本为8以上时, jdbc驱动为 com.mysql.cj.jdbc.Driver
mysql-connector-java --版本为5时, jdbc驱动为 com.mysql.jdbc.Driver
2.配置数据源(application. yml)
#配置数据源
spring:
datasource:
url: jdbc:mysql://192.168.3.88:3366/test01?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: Biaopu8888.
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
#配置映射文件的扫描
mapper-location: classpath*:com/demo/dao/*.xml
#配置别名的扫描
type-aliases-package: com.demo.entity
3.提供映射接口、映射文件
StuMapper.java
/**
* @DATE 2023/2/9
* @DESCRIPTION
* @Mapper 配置映射接口的扫描
**/
@Mapper
public interface StuMapper {
public List<Student> stuList();
public Student stuByone();
}
StuMapper.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="com.demo.dao.StuMapper">
<select id="stuList" resultType="com.demo.entity.Student">
select * from m_t_student
</select>
<select id="stuByone" resultType="com.demo.entity.Student">
select * from m_t_student
</select>
</mapper>
StudentController.java
package com.demo.controller;
import com.demo.dao.StuMapper;
import com.demo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @DATE 2023/2/7
* @DESCRIPTION
**/
@RestController
@RequestMapping("/stu")
public class StudentController {
@Autowired
StuMapper studentDao;
@RequestMapping("/list")
public List<Student> StuList(){
return studentDao.stuList();
}
@RequestMapping("/stuByone")
public Student stuByone(){
return studentDao.stuByone();
}
}
StuMapper.xml放在java文件夹中非rescources中时,需要添加如下配置
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>com/demo/dao/*.xml</include>
</includes>
</resource>
</resources>