Using spring + springboot + mybatis technology to realize the operation of adding, deleting, modifying and checking of enterprise employees

Time:2021-4-6

Business description

Requirement description

Any enterprise will involve the addition, deletion, modification and query of employees. In the current business system design, we need to design and implement the management of employee information.

Business framework analysis

In staff information management, it is necessary to add, modify, query and delete employee information, as shown in the figure
Using spring + springboot + mybatis technology to realize the operation of adding, deleting, modifying and checking of enterprise employees

Analysis and design of project technical architecture

In the implementation process of the employee management module, we use the typical C / S architecture, the client is based on the browser, the server is tomcat, the database is mysql, and the specific application layer is based on the MVC hierarchical architecture.

Application analysis and selection of project technology stack

Client technology: HTML, CSS, JavaScript, bootstrap
Server technology: hikaricp, mybatis, spring, springboot, thymeleaf
Database technology: MySQL, SQL

Analysis and design of database and table

database initialized

Open the MySQL console, and then follow the steps below staff.sql Documents.
Step 1: log in to MySQL (Note: the server password should be set)

mysql –uroot –p*****

Step 2: set the console encoding mode

set names utf8;

Step 3: Implementation staff.sql File (remember not to open the file and copy it to the MySQL client to run, otherwise there will be garbled problem).

source d:/staff.sql

Step 4: after the script is executed successfully, execute the following statement before the client queries the data:

set names gbk;

among staff.sql The contents of the document are as follows:

Design and create database

If the database already exists, delete the database first. The code is as follows:

drop database if exists dbstaff;

To create a new database, the code is as follows:

create database dbstaff default character set utf8;

Create a staff table

Open the database, and the statement is as follows:

use dbstaff;

Create employee table in dbstaff database:

create table tb_staff(
     id bigint primary key auto_increment,
     name varchar(100) not null,
     gender varchar(10) not null,
     workingTime datetime not null
)engine=InnoDB;
insert into tb_staff values (null,'A','man',now());
insert into tb_staff values (null,'B','woman',now());
insert into tb_staff values (null,'C','woman',now());
insert into tb_staff values (null,'D','woman',now());
insert into tb_staff values (null,'E','man',now());
insert into tb_staff values (null,'F','man',now());
insert into tb_staff values (null,'G','woman',now()); 

Project environment initialization

Prepare for operation

1)JDK 1.8
2)Maven 3.6.3
3)IDEA 2020.2
4)MySQL 5.7+

Create project module

Open idea, and then create a project module based on the design, as shown in the figure:
Using spring + springboot + mybatis technology to realize the operation of adding, deleting, modifying and checking of enterprise employees
Specify the project core dependency when creating a project module
Using spring + springboot + mybatis technology to realize the operation of adding, deleting, modifying and checking of enterprise employees

Add project module dependency

MySQL driver

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

Srping JDBC provides the hikaricp connection pool

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

Mybatis resources

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.3</version>
</dependency>

Spring web dependency (built in a Tomcat service)

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Thymeleaf dependency (HTML template engine)

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Basic configuration of project module

Open the project module configuration file application.properties , and add the following contents (Note: server password password to use the set password):

#spring server
server.port=80
# spring datasource
spring.datasource.url=jdbc:mysql:///dbstaff?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=*****
# spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml
# spring log
logging.level.com.cy=debug
#spring thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Query and presentation of employee data

Business description

The employee information in the database is found out, and then presented in the client based on HTML technology.

Design and implementation of domain object

Set the staff object to encapsulate the employee information queried from the database. The code is as follows:

package com.cy.pj.staff.pojo;
import java.util.Date;
public class Staff {
    private Integer id;
    private String name;
    private String gender;
    private Date workingTime;
    @Override
 public String toString() {
        return "Staff{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", gender='" + gender + ''' +
                ", workingTime=" + workingTime +
                '}';
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public Date getWorkingTime() {
        return workingTime;
    }
    public void setWorkingTime(Date workingTime) {
        this.workingTime = workingTime;
    }
}

Design and implementation of data logic object (DAO) query method

The key steps are as follows

Step 1: define the staffdao interface. The code is as follows:

package com.cy.pj.staff.dao;
@Mapper
public interface StaffDao{

}

Step 2: define the brand query method in staffdao. The code is as follows:

List<Staff> findStaffs(String name);

Step 3: define SQL mapping based on query method
Create a mapper / staff directory in the resources directory and add it to the directory StaffMapper.xml The key codes are as follows:

<?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.cy.pj.staff.dao.StaffDao">
    <select id="findStaffs" resultType="com.cy.pj.staff.pojo.Staff">
        select id,name,gender,workingTime
        from tb_staff
        <if test="name!=null and name!=''">
            where name like concat("%",#{name},"%")
        </if>
    </select>
</mapper>

Where: concat is the string connection function provided in MySQL

Step 4: unit test the query method of data layer. The code is as follows:

package com.cy.staff.dao;
import com.cy.pj.staff.dao.StaffDao;
import com.cy.pj.staff.pojo.Staff;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class StaffDaoTest {
    @Autowired
 private StaffDao staffDao;
    @Test
 void testFindStaffs(){
        List<Staff> list = staffDao.findStaffs("C");
        for (Staff s:list){
            System.out.println(s);
        }
    }
}

Design and implementation of business logic object (service) query method

Business logic object is responsible for the specific business processing of the module, such as parameter verification, transaction control, permission control, logging, etc
Step 1: define business interface

package com.cy.pj.staff.service;
import com.cy.pj.staff.pojo.Staff;
import java.util.List;
public interface StaffService {
    
}

Step 2: add a brand query method to the staffservice interface

List<Staff>findStaffs(String name);

Step 3: define the staffservice interface implementation class staffserviceimpl

package com.cy.pj.staff.service.impl;
import com.cy.pj.staff.dao.StaffDao;
import com.cy.pj.staff.pojo.Staff;
import com.cy.pj.staff.service.StaffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StaffServiceImpl implements StaffService {
    private static final Logger log= LoggerFactory.getLogger(StaffServiceImpl.class);
    @Autowired
 private StaffDao staffDao;
    public List<Staff> findStaffs(String name) {
        long t1 = System.currentTimeMillis();
        List<Staff> list = staffDao.findStaffs(name);
        long t2 = System.currentTimeMillis();
        log.info("findStaffs->time->{}",(t2-t1));
        return list;
    }
}

Step 4: define the unit test class of staffservice interface method, and test and analyze the business

package com.cy.staff.service;
import com.cy.pj.staff.pojo.Staff;
import com.cy.pj.staff.service.StaffService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class StaffServiceTests {
    @Autowired
 private StaffService staffService;
    @Test
 void testFindStaffs(){
        List<Staff> list = staffService.findStaffs("");
        for (Staff s:list){
            System.out.println(s);
        }
    }
}

Design and implementation of query method for controller

In the control logic object, it is mainly responsible for request and response logic control, such as request URL mapping, parameter mapping, request mode, result set encapsulation, parsing, response design, etc.
Step 1: define the controller class

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]