这里是接上一篇(示例代码中也包含了前面一篇的相关内容),知道如何连接MySQL数据库之后,实际中,我们多半不会直接用JDBC连接MYSQL数据库,而是使用这里的MyBatis。
MyBatis是一个持久层框架,定义了SQL、存储过程等映射,通过它避免了开发人员自己写数据库相关的代码。接下来是一个示例。
1、依赖配置添加
在connnect/pom.xml
文件中添加mybatis依赖,如下:
4.0.0
com.space.mysql
connnect
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
8.0.11
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.0
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
:
insert into Student(id, name, age) VALUES (#{id}, #{name}, #{age})
update Student set name = #{name}, age = #{age} where id = #{id}
delete from Student where id = #{id}
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 queryStudentById(int id);
List 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 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 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 queryStudentList() {
List 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 queryStudentList(){
List 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";
}
}
到这里,代码就都结束了,最后的目录结构如下图。
运行之后,浏览器访问如下链接都可以得到预期的输出。
http://localhost:8080/queryStudentList
http://localhost:8080/queryStudentById
http://localhost:8080/addStudent
http://localhost:8080/updateStudent
http://localhost:8080/deleteStudent