一、项目结构
1.导入依赖
<?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>org.example</groupId>
<artifactId>vue-service</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--JSON转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<!--mybatis的springboot支持-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
</project>
2.controller层
package org.example.vue.controller;
import com.alibaba.fastjson.JSON;
import org.example.vue.pojo.Person;
import org.example.vue.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
//@CrossOrigin(origins = "http://127.0.0.1:5500") // 后端解决跨域;指定允许的来源
public class PersonController {
@Autowired
private PersonService personService;
/**
* 查询用户,根据用户id查询单个用户信息
*
* @param personId 用户id,如果方法中形参与路径传来形参名字一致,那么@PathVariable("id")可简写为@PathVariable,
* 此处为了演示,一般写一致(personId写为id)。
* @return 返回json串,正常开发中应该返回查到的Person对象
*/
@GetMapping("/findPerson/{id}") //请求路径为 http://localhost:8081/api/findPerson/id
public String findPerson(@PathVariable("id") String personId) {
Person person = personService.findPerson(personId);
return JSON.toJSONString(person); //将对象转为json字符串
}
/**
* 添加用户,前端传来json对象,后端用对象接收
*
* @param person Person实体类
*/
@PostMapping("/addPerson")
public void addPerson(@RequestBody Person person) {
personService.addPerson(person);
}
/**
* 修改用户,根据用户id修改,注意id必须是数据库中存在,实际开发中不会有该问题
*
* @param person Person实体类
*/
@PutMapping("/editPersonById")
public void editPersonById(@RequestBody Person person) {
personService.editPersonById(person);
}
/**
* 删除用户,根据用户id删除
* @param id 用户id
*/
@DeleteMapping("deletePersonById")//请求路径为 http://localhost:8081/api/deletePersonById?id=xxx
public void deletePersonById(@RequestParam Integer id) {
personService.deletePersonById(id);
}
}
3.mapper层
package org.example.vue.mapper;
import org.example.vue.pojo.Person;
public interface PersonMapper {
Person findPerson(String id);
void addPerson(Person person);
void editPersonById(Person person);
void deletePersonById(Integer id);
}
4.pojo实体类
package org.example.vue.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable { //实现序列化接口(对象的状态 <==> 字节序列)
private Integer id;
private String username;
private String password;
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 指定日期格式
private Date orderTime;
}
5.service层
PersonService接口
package org.example.vue.service;
import org.example.vue.pojo.Person;
public interface PersonService {
Person findPerson(String id);
void addPerson(Person person);
void editPersonById(Person person);
void deletePersonById(Integer id);
}
PersonService实现类
package org.example.vue.service;
import org.example.vue.mapper.PersonMapper;
import org.example.vue.pojo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonServiceImp implements PersonService {
@Autowired
private PersonMapper personMapper;
@Override
public Person findPerson(String id) {
return personMapper.findPerson(id);
}
@Override
public void addPerson(Person person) {
personMapper.addPerson(person);
}
@Override
public void editPersonById(Person person) {
personMapper.editPersonById(person);
}
@Override
public void deletePersonById(Integer id) {
personMapper.deletePersonById(id);
}
}
6.启动类
package org.example.vue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("org.example.vue.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7.PersonMapper.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.example.vue.mapper.PersonMapper">
<!-- 查询 -->
<select id="findPerson" resultType="org.example.vue.pojo.Person">
select *
from person
where id = #{id}
</select>
<!-- 新增 -->
<insert id="addPerson" parameterType="org.example.vue.pojo.Person">
INSERT INTO person (username, password, age, order_time)
VALUES (#{username}, #{password}, #{age}, #{orderTime})
</insert>
<!-- 修改 -->
<update id="editPersonById" parameterType="org.example.vue.pojo.Person">
update person
set username = #{username},
password = #{password},
age = #{age},
order_time = #{orderTime}
where id = #{id}
</update>
<!-- 删除 -->
<delete id="deletePersonById" parameterType="org.example.vue.pojo.Person">
delete
from person
where id =
#{id}
</delete>
</mapper>
8.application.yml
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #mysql5版本把.cj去掉,此处为mysql8.0
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai #test改成自己的数据库名
username: root
password: "123456"
mybatis:
mapper-locations: classpath:mybatis/*.xml
#目的是为了省略resultType里的代码量,可不加
# type-aliases-package: com.example.pojo
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
二、Sql
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 80033 (8.0.33)
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 80033 (8.0.33)
File Encoding : 65001
Date: 29/04/2024 18:21:33
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
`order_time` datetime NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES (1, '李白', '123', 18, '2024-04-29 15:06:30');
INSERT INTO `person` VALUES (2, '张飞', '123456', 18, '2024-04-16 23:06:30');
INSERT INTO `person` VALUES (3, '张飞修改', '122222', 20, '2024-04-03 01:06:30');
INSERT INTO `person` VALUES (4, '朵朵', '123456', 18, '2024-04-26 23:06:30');
SET FOREIGN_KEY_CHECKS = 1;
三、Postman准备
postman准备
创建-Collections
创建请求-Request
请求介绍
1 查询:
请求方式:Get 请求路径:http://localhost:8081/api/findPerson/1
2 新增:
请求方式:Post 请求路径:http://localhost:8081/api/findPerson/1http://localhost:8081/api/addPerson
传递数据:
{
"username": "优雅",
"password": "12345",
"age": 18,
"orderTime": "2024-04-26 15:06:30"
}
http://localhost:8081/api/findPerson/1
3 编辑:
请求方式:Put 请求路径:http://localhost:8081/api/editPersonById
4 删除:
请求方式:DELETE 请求路径:http://localhost:8081/api/deletePersonById?id=5
测试
点击Send访问后端,测试,如出错可观察postman、java终端提示错误
补充
service层和mapper层和上面类似。
1 查询所有
controller层
/**
* 查询所有
* @return List集合
*/
@GetMapping("findAllPerson")
public List<Person> findAllPerson(){
return personService.findAllPerson();
}
PersonMapper.xml
<!-- 查询所有 resultType 属性指定了查询结果的类型,这里为 Person,表示每一行记录都会映射到一个 Person 对象 -->
<select id="findAllPerson" resultType="org.example.vue.pojo.Person">
select *
from person
</select>
Postman准备
请求方式:Get 请求路径:http://localhost:8081/api/findAllPerson
2 新增多个
controller层
/**
* 一次插入多条记录
* @param personList 用一个List集合接收
*/
@PostMapping("/addPersonList")
public void addPersonList(@RequestBody List<Person> personList){
System.out.println("controller:"+personList);
personService.addPersonList(personList);
}
PersonMapper.xml
<!-- 插入List集合 -->
<insert id="addPersonList" parameterType="java.util.List">
insert into person(username, password, age, order_time)values
<foreach collection="personList" item="person" separator=",">
(#{person.username}, #{person.password}, #{person.age}, #{person.orderTime})
</foreach>
</insert>
Postman准备
请求方式:Post 请求路径:http://localhost:8081/api/addPersonList
传递数据:
[
{
"username": "优雅",
"password": "12345",
"age": 18,
"orderTime": "2024-04-26 15:06:30"
},
{
"username": "优雅2",
"password": "12345",
"age": 18,
"orderTime": "2024-04-26 15:06:30"
}
]