当前位置:网站首页>3. addition, deletion, modification and query of employees
3. addition, deletion, modification and query of employees
2022-06-24 10:15:00 【xjhqre】
Addition, deletion, modification and query of employees
1、 New employees
1.1、 Save employee method
establish save Method , route :com/itheima/reggie/controller/EmployeeController.java
@PostMapping
public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
log.info(" New employees , Employee information :{}", employee.toString());
// Set the initial password 123456, Need to carry out md5 Encryption processing
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
// Get the current login user's id
Long empId = (Long) request.getSession().getAttribute("employee");
// Set the name of the person who added the employee information id
employee.setCreateUser(empId);
employee.setUpdateUser(empId);
// Store employee information in the database
employeeService.save(employee);
return R.success(" New employees ");
}
1.2、 Global exception
Create a global exception capture class GlobalExceptionHandler, Catch the exception of the class annotated with the specified annotation
package com.itheima.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;
/** * @Author: xjhqre * @DateTime: 2022/6/17 14:17 */
// It's marked RestController and Controller Annotated classes to intercept
@Slf4j
@RestControllerAdvice(annotations = {
RestController.class, Controller.class})
public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
log.error(ex.getMessage());
if (ex.getMessage().contains("Duplicate entry")) {
String[] split = ex.getMessage().split(" ");
String msg = split[2] + " Already exists ";
return R.error(msg);
}
return R.error(" Unknown error ");
}
}
2、 Paging query of employee list
2.1、 To configure mybatis-plus Pagination plug-in for
stay config Create under directory MybatisPlusConfig
package com.itheima.reggie.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** * @Author: xjhqre * @DateTime: 2022/6/17 14:45 */
@Configuration
public class MybatisPlusConfig {
/** * Configure paging plug-ins */
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
2.2 Query method writing
establish page Method , route :com/itheima/reggie/controller/EmployeeController.java
// Query employee information by page
@GetMapping("/page")
public R<Page<Employee>> page(int page, int pageSize, String name) {
log.info("page = {}, pageSize = {}, name = {}", page, pageSize, name);
// Construct a paging constructor
Page<Employee> pageInfo = new Page<>(page, pageSize);
// Construct condition constructors
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
// Add filter conditions
queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
// Add sorting criteria
queryWrapper.orderByDesc(Employee::getUpdateTime);
// Execute the query
employeeService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
2.3 Test paging
If you want to test the paging button function , You can add multiple pieces of data or modify the display quantity of each page
To modify the display quantity per page, you can modify the front end list.html
file , route :backend/page/member/list.html
Modify the following two values :
3、 Enable / Disable employee account
When querying the employee list , The back end will send the information to each employee in the front end , However, due to the id The attribute is Long Type and length exceeds js The maximum length that can be handled , Results in a loss of accuracy .
resolvent :
The custom message converter replaces the default message converter , In the custom Converter Long Type into String Type is sent to the front end .
3.1 To write JacksonObjectMapper class
stay common
Create under directory JacksonObjectMapper
.
package com.itheima.reggie.common;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/** * Object mapper : be based on jackson take Java Object to json, Or will json To Java object * take JSON It can be interpreted as Java The process of an object is called [ from JSON Deserialization Java object ] * from Java Object to generate JSON The process is called [ serialize Java Object to JSON] */
public class JacksonObjectMapper extends ObjectMapper {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public JacksonObjectMapper() {
super();
// No exception is reported when an unknown attribute is received
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
// When deserializing , Property does not exist
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(BigInteger.class, ToStringSerializer.instance)
.addSerializer(Long.class, ToStringSerializer.instance)
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
// Registration function module for example , You can add custom serializers and deserializers
this.registerModule(simpleModule);
}
}
3.2、 Expand Spring MVC Message converter for
stay WebMvcConfig
Rewriting in extendMessageConverters
Method
/** * Expand mvc Message converter of framework * @param converters */
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info(" Extended message converter ...");
// Create a message repeater object
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
// Set the object circulator , Bottom use Jackson take java Object to json
messageConverter.setObjectMapper(new JacksonObjectMapper());
// Append the above message converter object to mvc In the converter collection of the framework
converters.add(0, messageConverter);
}
3.3 Write update methods
stay EmployeeController
Created in update
Method
No changes are seen in the code status, Because the value is passed in from the front end , It has been encapsulated in the formal parameter employee in
/** * Update employee information * @param request * @param employee * @return */
@PutMapping
public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
Long empId = (Long) request.getSession().getAttribute("employee");
employee.setUpdateUser(empId);
employee.setUpdateTime(LocalDateTime.now());
employeeService.updateById(employee);
return R.success(" Employee information modified successfully ");
}
4、 Edit employee information
Process description :
- When you click the Edit button , The page jumps to add.html, And in url Carry parameters in [ staff id]
- stay add.html Page to obtain url Parameters in
- send out ajax request , Request server , At the same time, submit the employee id Parameters
- Server receives request , According to the staff id Query employee information , Send employee information to JSON Form response to the page
- The page receives the response from the server JSON data , adopt vue Data binding for employee information echo
- Click the save button , send out ajax request , Change the employee information in the page to JSON Submit to the server , It's called update Method
- The server receives employee information , And process it , Respond to the page after completion
- The page will respond after receiving the server response information
add.html The page is a public page , Adding and editing employees are operated on this page
4.1 How to create echo data
stay EmployeeController
Class getById
Method
/** * according to id Query employee information * @param id * @return */
@GetMapping("/{id}")
public R<Employee> getById(@PathVariable(value = "id") Long id) {
log.info(" according to id Query employee information ...");
Employee employee = employeeService.getById(id);
if (employee != null) {
return R.success(employee);
}
return R.error(" No corresponding employee information is found ");
}
4.2 Test and modify employee information
边栏推荐
- Phpstrom code formatting settings
- 2022-06-23: given a nonnegative array, select any number to make the maximum cumulative sum a multiple of 7, and return the maximum cumulative sum. N is larger, to the 5th power of 10. From meituan. 3
- Detailed explanation of PHP singleton mode
- Regular matching mobile number
- Indexeddb local storage, homepage optimization
- Record the range of data that MySQL update will lock
- SQL Sever中的窗口函数row_number()rank()dense_rank()
- 4.分类管理业务开发
- How to standardize data center infrastructure management process
- CVPR 2022 oral | NVIDIA proposes an efficient visual transformer network a-vit with adaptive token. The calculation of unimportant tokens can be stopped in advance
猜你喜欢
微信小程序學習之 實現列錶渲染和條件渲染.
时尚的弹出模态登录注册窗口
队列Queue
Canvas draw picture
CVPR 2022 Oral | 英伟达提出自适应token的高效视觉Transformer网络A-ViT,不重要的token可以提前停止计算
H5网页如何在微信中自定义分享链接
Groovy obtains Jenkins credentials through withcredentials
Tutorial (5.0) 08 Fortinet security architecture integration and fortixdr * fortiedr * Fortinet network security expert NSE 5
SQL Server AVG function rounding
形状变化loader加载jsjs特效代码
随机推荐
numpy.logical_or
MySQL data advanced
5.菜品管理业务开发
SSH Remote Password free login
dedecms模板文件讲解以及首页标签替换
时尚的弹出模态登录注册窗口
JS singleton mode
415 binary tree (144. preorder traversal of binary tree, 145. postorder traversal of binary tree, 94. inorder traversal of binary tree)
NVIDIA's CVPR 2022 oral is on fire! 2D images become realistic 3D objects in seconds! Here comes the virtual jazz band!
Use of vim
The great charm of cookies
解决微信小程序rich-text富文本标签内部图片宽高自适应的方法
How to standardize data center infrastructure management process
1.项目环境搭建
形状变化loader加载jsjs特效代码
PostgreSQL DBA quick start - source compilation and installation
分布式 | 如何与 DBLE 进行“秘密通话”
小程序 rich-text中图片点击放大与自适应大小问题
2021-08-17
简单的价格表样式代码