The notes are reproduced from AcWing’s SpringBoot Framework course handouts, course link:AcWing SpringBoot Framework course.
This section implements a data table for storing user Bot information and an API for adding, deleting, modifying and querying Bot data.
1. Update database table
We need to create a table to save Bot information. Create a new bot
table containing the following columns:
id: int
: Non-null, auto-increment, unique, primary key.user_id: int
: Not empty. Note:pojo
needs to be defined asuserId
, and the name inqueryWrapper
is stilluser_id
.title: varchar(100)
。description: varchar(300)
。content:varchar(10000)
。rating: int
: The default value is 1500.createtime: datetime
, Note: Annotation defining date format inpojo
:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
.modifytime: datetime
。
You can use the following SQL statement to create the table with one click:
CREATE TABLE `kob`.`bot` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int NOT NULL,
`title` varchar(100) NULL,
`description` varchar(300) NULL,
`content` varchar(10000) NULL,
`rating` int NULL DEFAULT 1500,
`createtime` datetime NULL,
`modifytime` datetime NULL,
PRIMARY KEY (`id`)
);
After creating the database table, we need to create onepojo
and create the class in the pojo
directory:Bot
a>
package com.kob.backend.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bot {
@TableId(value = "id", type = IdType.AUTO) // 声明id为自增类型
private Integer id;
private Integer userId; // 注意驼峰命名,userId之后会被解析为user_id,别写成userID,因为这样会解析成user_i_d
private String title;
private String description;
private String content;
private Integer rating;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 注意日期格式的设置
private Date createtime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date modifytime;
}
Then you can implement mapper
and create the interface in the mapper
directory: BotMapper
package com.kob.backend.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kob.backend.pojo.Bot;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BotMapper extends BaseMapper<Bot> {
}
2. Implement backend API
First create the package under the service.user
package to store the Service code related to Bot, and then create it under the package Create a package to store the corresponding Service implementation code, and finally create a package under the package to store the Controller. bot
service.impl.user
bot
controller.user
bot
We need to implement the following four APIs:
/user/bot/add/
: Create a Bot./user/bot/remove/
: Delete a Bot./user/bot/update/
: Modify a Bot./user/bot/getlist/
: Query the Bot list.
Create the Service interfaces of these four APIs under the service.user.bot
package:
(1)AddService
:
package com.kob.backend.service.user.bot;
import java.util.Map;
public interface AddService {
Map<String, String> add(Map<String, String> data);
}
(2)RemoveService
:
package com.kob.backend.service.user.bot;
import java.util.Map;
public interface RemoveService {
Map<String, String> remove(Map<String, String> data);
}
(3)UpdateService
:
package com.kob.backend.service.user.bot;
import java.util.Map;
public interface UpdateService {
Map<String, String> update(Map<String, String> data);
}
(4)GetListService
:
package com.kob.backend.service.user.bot;
import com.kob.backend.pojo.Bot;
import java.util.List;
public interface GetListService {
List<Bot> getList(); // 根据用户信息获取Bot,用户信息存放在令牌中,因此不用传参数
}
Next, create the implementations of these four Service interfaces under the service.impl.user.bot
package:
(1)AddServiceImpl
:
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AddServiceImpl implements AddService {
@Autowired
private BotMapper botMapper;
@Override
public Map<String, String> add(Map<String, String> data) {
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
User user = loginUser.getUser(); // 获取当前登录的用户
String title = data.get("title");
String description = data.get("description");
String content = data.get("content");
Map<String, String> res = new HashMap<>();
if (title == null || title.isEmpty()) {
res.put("result", "The title can't be empty!");
return res;
}
if (title.length() > 100) {
res.put("result", "Title length can't exceed 100!");
return res;
}
if (description == null || description.isEmpty()) {
description = "这个用户很懒,什么也没留下~";
}
if (description.length() > 300) {
res.put("result", "Description length can't exceed 300!");
return res;
}
if (content == null || content.isEmpty()) {
res.put("result", "The code can't be empty!");
return res;
}
if (content.length() > 10000) {
res.put("result", "Code length can't exceed 10000!");
return res;
}
Date now = new Date();
Bot bot = new Bot(null, user.getId(), title, description, content, 1500, now, now);
botMapper.insert(bot);
res.put("result", "success");
return res;
}
}
(2)RemoveServiceImpl
:
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.RemoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class RemoveServiceImpl implements RemoveService {
@Autowired
private BotMapper botMapper;
@Override
public Map<String, String> remove(Map<String, String> data) {
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
User user = loginUser.getUser(); // 需要判断要删除的Bot是不是当前登录用户的Bot
int bot_id = Integer.parseInt(data.get("bot_id"));
Bot bot = botMapper.selectById(bot_id);
Map<String, String> res = new HashMap<>();
if (bot == null) {
res.put("result", "Bot doesn't exist!");
return res;
}
if (!bot.getUserId().equals(user.getId())) {
res.put("result", "No permission to delete the bot!");
return res;
}
botMapper.deleteById(bot_id);
res.put("result", "success");
return res;
}
}
(3)UpdateServiceImpl
:
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class UpdateServiceImpl implements UpdateService {
@Autowired
private BotMapper botMapper;
@Override
public Map<String, String> update(Map<String, String> data) {
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
User user = loginUser.getUser();
int bot_id = Integer.parseInt(data.get("bot_id"));
String title = data.get("title");
String description = data.get("description");
String content = data.get("content");
Map<String, String> res = new HashMap<>();
if (title == null || title.isEmpty()) {
res.put("result", "The title can't be empty!");
return res;
}
if (title.length() > 100) {
res.put("result", "Title length can't exceed 100!");
return res;
}
if (description == null || description.isEmpty()) {
description = "这个用户很懒,什么也没留下~";
}
if (description.length() > 300) {
res.put("result", "Description length can't exceed 300!");
return res;
}
if (content == null || content.isEmpty()) {
res.put("result", "The code can't be empty!");
return res;
}
if (content.length() > 10000) {
res.put("result", "Code length can't exceed 10000!");
return res;
}
Bot bot = botMapper.selectById(bot_id);
if (bot == null) {
res.put("result", "Bot doesn't exist!");
return res;
}
if (!bot.getUserId().equals(user.getId())) {
res.put("result", "No permission to update the bot!");
return res;
}
Bot new_bot = new Bot(bot.getId(), user.getId(), title, description, content, bot.getRating(), bot.getCreatetime(), new Date());
botMapper.updateById(new_bot);
res.put("result", "success");
return res;
}
}
(4)GetListServiceImpl
:
package com.kob.backend.service.impl.user.bot;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.GetListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GetListServiceImpl implements GetListService {
@Autowired
private BotMapper botMapper;
@Override
public List<Bot> getList() {
UsernamePasswordAuthenticationToken authenticationToken =
(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
User user = loginUser.getUser();
QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", user.getId());
return botMapper.selectList(queryWrapper);
}
}
Finally create the corresponding Controller under the controller.user.bot
package:
(1)AddController
:
package com.kob.backend.controller.user.bot;
import com.kob.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class AddController {
@Autowired
private AddService addService;
@PostMapping("/user/bot/add/")
public Map<String, String> add(@RequestParam Map<String, String> data) {
return addService.add(data);
}
}
(2)RemoveController
:
package com.kob.backend.controller.user.bot;
import com.kob.backend.service.user.bot.RemoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class RemoveController {
@Autowired
private RemoveService removeService;
@PostMapping("/user/bot/remove/")
public Map<String, String> remove(@RequestParam Map<String, String> data) {
return removeService.remove(data);
}
}
(3)UpdateController
:
package com.kob.backend.controller.user.bot;
import com.kob.backend.service.user.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class UpdateController {
@Autowired
private UpdateService updateService;
@PostMapping("/user/bot/update/")
public Map<String, String> update(@RequestParam Map<String, String> data) {
return updateService.update(data);
}
}
(4)GetListController
:
package com.kob.backend.controller.user.bot;
import com.kob.backend.pojo.Bot;
import com.kob.backend.service.user.bot.GetListService;
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;
@RestController
public class GetListController {
@Autowired
private GetListService getListService;
@GetMapping("/user/bot/getlist/")
public List<Bot> getList() {
return getListService.getList();
}
}