SpringBoot中MyBatis的使用入门示例
这里是接上一篇(示例代码中也包含了前面一篇的相关内容),知道如何连接MySQL数据库之后,实际中,我们多半不会直接用JDBC连接MYSQL数据库,而是使用这里的MyBatis。
MyBatis是一个持久层框架,定义了SQL、存储过程等映射,通过它避免了开发人员自己写数据库相关的代码。接下来是一个示例。
1、依赖配置添加
在connnect/pom.xml
文件中添加mybatis依赖,如下:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.space.mysql</groupId>
<artifactId>connnect</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
</project>
2、添加在应用配置文件中添加MyBatis相关配置
主要是说明下数据库记录映射的类和mapper配置文件的路径信息。
application.properties
:
spring.datasource.username=root
spring.datasource.password=lfqylfqy
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis相关配置
#数据库记录映射类所在的包和mapper文件存放的位置
mybatis.type-aliases-package=com.space.mysql.connect.domain
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
新增一个mapper文件,并在其中定义相关的sql语句。
mybatis/mapper/StudentMapper.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.space.mysql.connect.mapper.StudentMapper">
<select id="queryStudentList" resultType="com.space.mysql.connect.domain.Student">
select * from student
</select>
<select id="queryStudentById" resultType="com.space.mysql.connect.domain.Student">
select * from student where id = #{id}
</select>
<insert id="addStudent" parameterType="com.space.mysql.connect.domain.Student">
insert into Student(id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
<update id="updateStudent" parameterType="com.space.mysql.connect.domain.Student">
update Student set name = #{name}, age = #{age} where id = #{id}
</update>
<delete id="deleteStudent" parameterType="int">
delete from Student where id = #{id}
</delete>
</mapper>
3、Java代码编写
3.1 新增一个和数据库表中记录对应的java类
这里借用之前的表结构:
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 51
Server version: 8.0.20 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> describe student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
| age | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql>
com.space.mysql.connect.domain.Student
:
package com.space.mysql.connect.domain;
/**
* Created by chengxia on 2021/12/11.
*/
public class Student {
private int id;
private String name;
private int age;
public Student(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;
}
}
3.2 新增一个Mapper接口对应mapper配置文件
这个接口可以结合配置文件,对应到sql语句。
com.space.mysql.connect.mapper.StudentMapper
:
package com.space.mysql.connect.mapper;
import com.space.mysql.connect.domain.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* Created by chengxia on 2021/12/11.
*/
@Mapper
public interface StudentMapper {
List<Student> queryStudentById(int id);
List<Student> queryStudentList();
void addStudent(Student stu);
void updateStudent(Student stu);
void deleteStudent(int id);
}
3.3 新增数据库Service类对数据库操作进行包装(调用mapper)
这里将服务多抽象了一层接口。
服务接口类com.space.mysql.connect.service.StudentServiceInterface
:
package com.space.mysql.connect.service;
import com.space.mysql.connect.domain.Student;
import java.util.List;
/**
* Created by chengxia on 2021/12/12.
*/
public interface StudentServiceInterface {
Student queryStudentById(int id);
List<Student> queryStudentList();
void addStudent(Student stu);
void updateStudent(Student stu);
void deleteStudent(int id);
}
服务实现类com.space.mysql.connect.service.StudentService
:
package com.space.mysql.connect.service;
import com.space.mysql.connect.domain.Student;
import com.space.mysql.connect.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by chengxia on 2021/12/12.
*/
@Service
public class StudentService implements StudentServiceInterface {
@Autowired
private StudentMapper stuMapper;
@Override
public Student queryStudentById(int id) {
List<Student> studentList = stuMapper.queryStudentById(id);
if(studentList != null && studentList.size() > 0) {
System.out.println(studentList.get(0));
return studentList.get(0);
}else{
return null;
}
}
@Override
public List<Student> queryStudentList() {
List<Student> studentList = stuMapper.queryStudentList();
for (Student stu: studentList){
System.out.println(stu);
}
return studentList;
}
@Override
public void addStudent(Student stu) {
stuMapper.addStudent(new Student(stu.getId(), stu.getName(), stu.getAge()));
}
@Override
public void updateStudent(Student stu) {
stuMapper.updateStudent(new Student(stu.getId(),stu.getName(), stu.getAge()));
}
@Override
public void deleteStudent(int id) {
stuMapper.deleteStudent(id);
}
}
3.4 应用启动类中增加mapper等类的扫描包路径
这一步必不可少,不然会报错mapper类的bean找不到。
Consider defining a bean of type 'com.space.mysql.connect.mapper.StudentMapper' in your configuration.
com.space.mysql.connect.main.Application
:
package com.space.mysql.connect.main;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Created by chengxia on 2021/12/7.
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.space.mysql.connect.controller","com.space.mysql.connect.service"})
@MapperScan(value = "com.space.mysql.connect.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4、写一个测试的controller类
这里简单的写一个controller类,调用前面的service实现和数据库交互。
com.space.mysql.connect.controller.StudentController
package com.space.mysql.connect.controller;
import com.space.mysql.connect.domain.Student;
import com.space.mysql.connect.service.StudentService;
import com.space.mysql.connect.service.StudentServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by chengxia on 2021/12/12.
*/
@RestController
public class StudentController {
@Autowired
private StudentServiceInterface stuService;
@GetMapping("/queryStudentList")
public List<Student> queryStudentList(){
List<Student> stuList = stuService.queryStudentList();
return stuList;
}
@GetMapping("/queryStudentById")
public Student queryStudentById(){
Student stuTmp = stuService.queryStudentById(2);
return stuTmp;
}
@GetMapping("/addStudent")
public String addStudent(){
stuService.addStudent(new Student(3,"Tim", 36));
return "insert Tim ok, id = 3";
}
@GetMapping("/updateStudent")
public String updateStudent(){
stuService.updateStudent(new Student(3,"MMPP", 36));
return "modify paopao into MMPP!";
}
@GetMapping("/deleteStudent")
public String deleteStudent(){
stuService.deleteStudent(3);
return "deleted id = 3";
}
}
到这里,代码就都结束了,最后的目录结构如下图。
image.png
运行之后,浏览器访问如下链接都可以得到预期的输出。
http://localhost:8080/queryStudentList
http://localhost:8080/queryStudentById
http://localhost:8080/addStudent
http://localhost:8080/updateStudent
http://localhost:8080/deleteStudent