使用MyBatis框架操作数据,在SpringBoot框架集成MyBatis,项目整体结构
前提:准备一张student表。
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int NOT NULL COMMENT '主键',
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名',
`age` int DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Records of user
-- ----------------------------
BEGIN;
INSERT INTO `student` (`id`, `name`, `age`) VALUES (1, '小强', 20);
INSERT INTO `student` (`id`, `name`, `age`) VALUES (2, '小刚', 27);
INSERT INTO `student` (`id`, `name`, `age`) VALUES (3, '小红', 22);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
使用步骤:
- 新建模块
springboot-005-mybatis
, 加入spring web, mybatis framework,mysql driver。其中mybatis起步依赖:完成mybatis对象自动配置,对象放在容器中.
- pom.xml中加入resource插件, 把src/main/java目录中的
**/*.xml
文件包含到classpath中,表示把src/main/java目录下任意一个目录下面的*.xml文件包含道resources中;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.12</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ben</groupId>
<artifactId>springboot-005-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-005-mybatis</name>
<description>springboot-005-mybatis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis起步依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!--resources插件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 写application.yml文件,配置数据库的连接信息。
server:
port: 8080
# mysql驱动
spring:
datasource:
url: jdbc:mysql://localhost:3306/spring6?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
# 开启支持put delete请求的过滤器,false的时候,delete/put请求执行不生效;
mvc:
hiddenmethod:
filter:
enabled: true
#指定mapper文件的位置
mybatis:
mapper-locations: classpath:mapper/*.xml
#指定mybatis的日志
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 创建实体类Student
package com.ben.model;
/**
* @Author: benjieqiang
* @CreateTime: 2023-05-27 21:24
* @Description: TODO
* @Version: 1.0
*/
public class Student {
private Integer id;
private String name;
private Integer age;
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
// ... getter and setter, toString
}
- 创建Dao接口 StudentMapper , 创建一个查询所有学生的方法
package com.ben.dao;
import com.ben.model.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @InterfaceName: StudentDao
* @Description: 使用Mapper注解,让springboot找到接口和他的xml 文件,创建实现类对象, 位置:在接口的上面
* @Author: benjieqiang
* @LastChangeDate: 2023/5/27 9:25 PM
* @Version: v1.0
*/
@Mapper
public interface StudentMapper {
/**
* @param student:
* @return int
* @description 插入新纪录
* @author benjieqiang
* @date 2023/5/28 5:41 PM
*/
int insert(Student student);
/**
* @param student:
* @return int
* @description 根据其他进行插入
* @author benjieqiang
* @date 2023/5/28 5:46 PM
*/
int insertSelective(Student student);
/**
* @param id: 主键
* @return int
* @description 根据id删除
* @author benjieqiang
* @date 2023/5/28 5:39 PM
*/
int deleteById(Integer id);
/**
* @param id:
* @return int
* @description 根据主键更新
* @author benjieqiang
* @date 2023/5/28 5:42 PM
*/
int updateById(Integer id);
/**
* @param student:
* @return int
* @description 根据其他更新
* @author benjieqiang
* @date 2023/5/28 5:45 PM
*/
int updateBySelective(Student student);
/**
* @param id:
* @return Student
* @description 根据id查询
* @author benjieqiang
* @date 2023/5/28 5:21 PM
*/
Student selectById(Integer id);
/**
* @param :
* @return List<Student>
* @description 查询所有学生
* @author benjieqiang
* @date 2023/5/27 9:25 PM
*/
List<Student> selectAll();
}
- 在resources文件夹下面新建mapper目录,创建Dao接口对应的Mapper文件, StudentMapper.xml文件, 写sql语句
<?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.ben.dao.StudentMapper">
<insert id="insert" parameterType="com.ben.model.Student" useGeneratedKeys="true">
insert into student (id, name, age) values (null, #{name}, #{age})
</insert>
<delete id="deleteById" parameterType="java.lang.Integer">
delete from student
where id = #{id,jdbcType=INTEGER}
</delete>
<update id="updateById" parameterType="java.lang.Integer">
update student
set name = #{name},
age = #{age}
where id = #{id}
</update>
<select id="selectAll" resultType="com.ben.model.Student">
select id,name,age from student
</select>
<select id="selectById" resultType="com.ben.model.Student">
select id,name,age from student where id = #{id}
</select>
</mapper>
- 创建Service层对象,创建StudentService接口和他的实现类StudentServiceImpl;
package com.ben.service;
import com.ben.model.Student;
import java.util.List;
/**
* @Author: benjieqiang
* @CreateTime: 2023-05-27 21:51
* @Description: TODO
* @Version: 1.0
*/
public interface StudentService {
int insertStudent(Student student);
int deleteStudentById(Integer id);
int updateStudentById(Integer id);
Student getStudentById(Integer id);
List<Student> getAllStudents();
}
package com.ben.service.impl;
import com.ben.dao.StudentMapper;
import com.ben.model.Student;
import com.ben.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: benjieqiang
* @CreateTime: 2023-05-27 21:52
* @Description: service实现类
* @Version: 1.0
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public int insertStudent(Student student) {
return studentMapper.insert(student);
}
@Override
public int deleteStudentById(Integer id) {
return studentMapper.deleteById(id);
}
@Override
public int updateStudentById(Integer id) {
return studentMapper.updateById(id);
}
@Override
public Student getStudentById(Integer id) {
return studentMapper.selectById(id);
}
@Override
public List<Student> getAllStudents() {
System.out.println("执行service中 getAllStudents方法");
return studentMapper.selectAll();
}
}
- 创建Controller对象,访问Service。
package com.ben.controller;
import com.ben.model.Student;
import com.ben.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: benjieqiang
* @CreateTime: 2023-05-27 21:54
* @Description: TODO
* @Version: 1.0
*/
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String addStudent(Student student) {
int count = studentService.insertStudent(student);
return "add status:" + count;
}
//PathVariable 从url获取数据;
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String deleteStudent(@PathVariable("id") Integer id) {
int count = studentService.deleteStudentById(id);
return "delete status: " + count;
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
@ResponseBody
public String updateStudent(@PathVariable("id") Integer id) {
System.out.println("执行update方法");
int count = studentService.updateStudentById(id);
return "update status:" + count;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public String getStudent(@PathVariable("id") Integer id) {
Student student = studentService.getStudentById(id);
System.out.println(student);
return student.toString();
}
@RequestMapping("/all")
@ResponseBody
public String getAllStudentsInfo() {
List<Student> allStudents = studentService.getAllStudents();
System.out.println(allStudents);
return allStudents.toString();
}
}
- 测试链接