Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Time:2021-9-27

Business description

Based on spring, mybatis, springboot and thymeleaf technologies, the addition, deletion, modification and query of commodity modules are realized.

Project environment initialization

preparation

1. MySQL(5.7)
2. JDK (1.8)
3. Maven (3.6.3)
4. STS(4.7.1)

database initialized

Open the MySQL console, and then execute the goods.sql file as follows.
Step 1: log in to MySQL.

mysql –uroot –proot

Step 2: set the console coding method.

set names utf8;

Step 3: execute the goods.sql file (remember not to open the file and copy it to the MySQL client for running).

source d:/goods.sql

The contents of the goods.sql file are as follows:

drop database if exists dbgoods;
create database dbgoods default character set utf8;
use dbgoods;
create table tb_goods(
     id bigint primary key auto_increment,
     name varchar(100) not null,
     remark text,
     createdTime datetime not null
)engine=InnoDB;
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());

Create project and add dependencies

STS based creation

Step 1: create a project based on start.spring.io and set basic information

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Step 2: specify the project core dependency when creating a project

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Step 3: analyze the structure of the project after it is created

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Create based on idea

Step 1: create a project based on start.spring.io and set basic information

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea
Step 2: specify the project core dependency when creating the project module

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Step 3: analyze the structure of the project module after it is created

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Project profile content initialization

#server
server.port=80
#server.servlet.context-path=/
#spring datasource
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

#spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml

#spring logging
logging.level.com.cy=debug

#spring thymeleaf
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

Project API architecture design

The API architecture design is shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Implementation of commodity query business

Business description

Query the commodity information from the commodity library and present the commodity information on the page, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Business timing analysis

Query all commodity information and analyze its business sequence, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

POJO class definition

Define the goods object to encapsulate the commodity information queried from the database.

package com.cy.pj.goods.pojo;
import java.util.Date;
public class Goods {
    private Long id;//id bigint primary key auto_increment
    private String name;//name varchar(100) not null
    private String remark;//remark text
    private Date createdTime;//createdTime datetime
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Date getCreatedTime() {
        return createdTime;
    }
    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }
    @Override
    public String toString() {
        return "Goods [id=" + id + ", name=" + name + ",   
        remark=" + remark + ", createdTime=" + createdTime + "]";
    }
}

Dao interface method and mapping definition

Define commodity query method and SQL mapping in goodsdao interface, and obtain all commodity information based on this method and SQL mapping. The code is as follows:

package com.cy.pj.goods.dao;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.cy.pj.goods.pojo.Goods;

@Mapper
public interface GoodsDao {
      @Select("select * from tb_goods")
      List<Goods> findGoods();
} 

Write unit test classes for test analysis:

package com.cy.pj.goods.dao;
import com.cy.pj.goods.pojo.Goods;
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 GoodsDaoTests {
    @Autowired
 private GoodsDao goodsDao;
    @Test
 void testFindGoods(){
        List<Goods> goodsList=goodsDao.findGoods();
        for(Goods g:goodsList){
            System.out.println(g);
        }
    }
}

Test results and problem analysis

  • The database cannot be connected, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • The URL configuration of connecting to the database is as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • The SQL map is repeatedly defined, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • Null pointer problem, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • SQL syntax problem, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Definition and implementation of service interface method

Goodsservice interface and commodity query method definition

package com.cy.pj.goods.service;
import java.util.List;
import com.cy.pj.goods.pojo.Goods;
public interface GoodsService {
      List<Goods> findGoods();
}

Definition and method implementation of goodsserviceimpl interface implementation class

package com.cy.pj.goods.service;
import java.util.List;
import com.cy.pj.goods.pojo.Goods;
@Service
public class GoodsServiceImpl implements GoodsService {
     @Autowired
     private GoodsDao goodsDao;
     @Override
     public List<Goods> findGoods(){
         return goodsDao.findGoods();
     }
}

Write unit test classes for test analysis

package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import org.junit.jupiter.api.Assertions;
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 GoodsServiceTests {
    @Autowired
 private GoodsService goodsService;
    @Test
 void testFindGoods(){
        List<Goods> goodsList=goodsService.findGoods();
        //Assertion testing (a common method in unit testing)
 Assertions.assertEquals(true, goodsList.size()>0);
    }
}

Test results and problem analysis

  • Dependency injection, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Definition and implementation of controller object method

Define the goodscontroller class, add the dogoodsui method, add the code to query the commodity information, store the queried commodity information in the model, and return to the goods page.

package com.cy.pj.goods.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
@Controller //@Service,@Component
@RequestMapping("/goods/")
public class GoodsController {
    //has a+di
    @Autowired
    private GoodsService goodsService;
    @RequestMapping("doGoodsUI")
    public String doGoodsUI(Model model) {
         //Call the business layer method to obtain the commodity information
         List<Goods> list= goodsService.findGoods();
         //Store data to request scope
         model.addAttribute("list", list);
         return "goods";//viewname
    }
    
}

Design and implementation of goods list page

Add the goods.html page in the templates / pages directory and the HTML element in the body. Use the thymeleaf tag attribute to obtain data inside the runtime. The code is as follows:

<table width="50%">
        <thead>
           <th>id</th>
           <th>name</th>
           <th>remark</th>
           <th>createdTime</th>
           <th>operation</th>
        </thead>
        <tbody>
           <tr th:each="g:${list}">
             <td th:text="${g.id}">1</td>
             <td th:text="${g.name}">MySQL</td>
             <td th:text="${g.remark}">DBMS</td>
             <td th:text="${#dates.format(g.createdTime, 'yyyy/MM/dd HH:mm')}">2020/07/03</td>
             <td><a>delete</a></td>
           </tr>
        </tbody>
  </table>

Thymeleaf is a template engine, which takes HTML as the template, can add custom tag attributes, can fill the data in the server model on the page, and then realize interaction with. Its official website is thymeleaf.org

Data presentation analysis on the goods page:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Start Tomcat for access test analysis

First, start tomcat, then open the browser, enter the access address in the address bar, obtain the server data and render it, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Bug and problem analysis during project startup and operation

  • The “?” symbol of STS console is shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • Service startup failed, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • There are no errors in the template, as shown in the figure:
  • The date format is incorrect, as shown in the figure:
  • The ${} content on the page is wrong, as shown in the figure:
  • The page date format is incorrect, as shown in the figure:
  • Dependency injection failed, as shown in the figure:
  • Null pointer exception (NullPointerException), as shown in the figure:

Implementation of commodity deletion business

Business description

After querying the commodity information from the commodity library, click the delete hyperlink on the page to delete the current line record based on the ID, as shown in the figure:

Business timing analysis

On the commodity presentation page, the user performs the deletion operation, and the deletion sequence is shown in the figure:

Dao interface method and mapping definition

Define the commodity deletion method and SQL mapping in the goodsdao interface. The code is as follows:

 @Delete("delete from tb_goods where id=#{id}")

 int deleteById(Integer id);

Definition and implementation of service interface method

Add and delete methods in goodsservice interface. The code is as follows:

int deleteById(Integer id);

Add the deletebyid method implementation in the goodsserviceimpl implementation class of goodsservice. The code is as follows.

@Override
    public int deleteById(Integer id) {
        long t1=System.currentTimeMillis();
        int rows=goodsDao.deleteById(id);
        long t2=System.currentTimeMillis();
        System.out.println("execute time:"+(t2-t1));
        return rows;
    }

Definition and implementation of controller object method

Add the dodeletebyid method in goodscontroller. The code is as follows:

 @RequestMapping("doDeleteById/{id}")
    public String doDeleteById(@PathVariable Integer id){
        goodsService.deleteById(id);
        return "redirect:/goods/doGoodsUI";
    } 

Note: Restful style is a software architecture coding style. It defines a URL format. Its URL syntax is / A / B / {C} / {D}. In this syntax structure, {} is a variable expression. If we want to get the value of the variable expression in the rest URL in the method parameter, we can use the @ pathvariable annotation to describe the parameter.

Delete hyperlink definition on the goods page

Add or delete hyperlinks in the goods.html page, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Thymeleaf official th: href application description, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

In the deletion operation, the description of the association between the client and the server code is shown in the figure:

Start Tomcat server for access test analysis

First, start tomcat, then open the browser, enter the access address in the address bar, obtain the server data and present it, and then click the delete button on the page, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

After the deletion is successful, the page is shown as follows:

Bug and problem analysis during project startup and operation

  • SQL mapping element definition problem, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • The client request parameters do not match the server parameters, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Implementation of commodity addition business

Business description

On the goods list page, click the Add button to add the page, then enter the product related information on the add page, and then save it to the database, as shown in the figure:

The product addition page is designed as shown in the figure:

Business timing analysis

On the product addition page, enter the product information and submit it to the server for saving. The timing analysis is shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Dao interface method and mapping definition

Add the interface method and SQL mapping for saving commodity information in goodsdao. The code is as follows:

@Insert("insert into tb_goods(name,remark,createdTime) 
values (#{name},#{remark},now())")
int insertObject(Goods entity);

Note: when the SQL statement is complex, you can also define the SQL into the mapping file (XML file).

Definition and implementation of service interface method

Add a business method in the goodsservice interface to add commodity information. The code is as follows:

int saveGoods(Goods entity);

Add the interface method implementation in goodsservivceimpl class. The code is as follows:

 @Override
    public int saveGoods(Goods entity) {
        int rows=goodsDao.insertObject(entity);
        return rows;
    } 

Definition and implementation of controller object method

Add a method to handle the commodity addition request in the goodscontroller class. The code is as follows:

@RequestMapping("doSaveGoods")
public String doSaveGoods(Goods entity) {
        goodsService.saveGoods(entity);
        return "redirect:/goods/doGoodsUI";
}

Add a method to return to the product addition page in the goodscontroller class. The code is as follows:

 @RequestMapping("doGoodsAddUI")
    public String doGoodsAddUI() {
        return "goods-add";
    } 

Design and implementation of adding pages to goods

Add the goods-add.html page in the pages directory of templates. The code is as follows

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css"> ul li {list-style-type: none;} </style>
</head>
<body>
<h1>The Goods Add Page</h1>
<form th:action="@{/goods/doSaveGoods}" method="post">
   <ul>
      <li>name:
      <li><input type="text" name="name">
      <li>remark:
      <li><textarea rows="5" cols="50" name="remark"></textarea>
      <li><input type="submit" value="Save">
   </ul>
</form>
</body>
</html>

When you add a hyperlink in the goods.html page, you can jump to the add page. The key codes are as follows:

< a th: href = "@{/ goods / dogoldsaddui}" > add a product</a>

Start Tomcat server for access test analysis

Step 1: start the web server and check whether the startup process is OK. If there is no problem, go to the next step.
Step 2: open the browser and enter in the address http://localhost/goods/doGood… ), the following interface appears, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Step 3: fill in the form on the add page, and then click Save to submit the form data to the server, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea
Step 4: add the form data submission process analysis in the page, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Bug and problem analysis during project startup and operation

  • The client displays 400 exception, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • 500 exception when saving, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • The database integrity constraint is abnormal, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Commodity modification business implementation

Business description

On the commodity list page, click the update option, query the current line record based on the commodity ID, and then update it to the goods update page, as shown in the figure:
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea
Select on the update page, modify the commodity information, and then click Update goods to submit the form data to the server for update

Business timing analysis

Time series design of querying commodity information based on ID
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea
Submit the data in the goods update page to the server for update timing design
Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Dao interface method and mapping definition

Add the method of querying commodity information based on ID and SQL mapping in goodsdao. The code is as follows:

@Select("select * from tb_goods where id=#{id}")
Goods findById(Integer id);

In goodsdao, add the method and SQL mapping of updating goods based on ID. the code is as follows:

 @Update("update tb_goods set name=#{name},remark=#{remark} where id=#{id}")
 int updateGoods(Goods goods);

Definition and implementation of service interface method

Add a method to query and update commodity information based on ID in goodsservice. The code is as follows:

Goods findById(Integer id);
int updateGoods(Goods goods);

In goodsserviceimpl, the method of querying and updating commodity information based on ID is as follows:

 @Override
    public Goods findById(Integer id) {
        //.....
        return goodsDao.findById(id);
    }
 @Override
    public int updateGoods(Goods goods) {
        return goodsDao.updateGoods(goods);
    }

Definition and implementation of controller object method

Add a method to query commodity information based on ID in goodscontroller. The code is as follows:

 @RequestMapping("doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model) {
        Goods goods=goodsService.findById(id);
        model.addAttribute("goods",goods);
        return "goods-update";
    }

Add a method to update product information in goodscontroller. The code is as follows:

 @RequestMapping("doUpdateGoods")
    public String doUpdateGoods(Goods goods) {
        goodsService.updateGoods(goods);
        return "redirect:/goods/doGoodsUI";
    }

Design and implementation of modified pages for goods

Add the goods-update.html page in the templates directory. The code design is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
  ul li {list-style-type: none} </style>
</head>
<body>
   <h1>The Goods Update Page</h1>
   <form th:action="@{/goods/doUpdateGoods}" method="post">
      <input type="hidden" name="id" th:value="${goods.id}">
      <ul>
        <li>name:
        <li><input type="text" name="name" th:value="${goods.name}">
        <li>remark:
        <li><textarea rows="3" cols="30" name="remark" th:text="${goods.remark}"></textarea>
        <li><input type="submit" value="Update Goods">
       </ul>
   </form>
</body>
</html>

Start Tomcat service for access test analysis

Start Tomcat service and access the product list page, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

On the list page, click the update option to enter the update page

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Update the form data on the update page, and then submit it. Enter the list page to view the update results, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Bug and problem analysis during project startup and operation

  • Page design analysis, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

  • Page source code analysis, as shown in the figure:

Spring, mybatis, springboot, and crud operation are integrated with spring MVC design idea

Summary

This section focuses on the comprehensive application of mybatis, spring MVC and thymeleaf technologies under the springboot project, focusing on understanding its business implementation process and problem solving process.

springboot