07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Time:2020-11-25

Business description

Based on the technology of spring, mybatis, springboot and thymeleaf, the operation of adding, deleting, modifying and checking commodity modules is realized.

database initialized

Open the MySQL console and follow the steps below goods.sql Documents.
Step 1: log in to MySQL.

mysql –uroot –proot

Step 2: set the console encoding mode.

set names utf8;

Step 3: Execution goods.sql File (remember not to open the file and copy it to the MySQL client).

source d:/goods.sql

among goods.sql The contents of the document 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 a project and add dependencies

Step 1: Based on start.spring.io Create a project and set up basic information

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module
Step 2: specify the project core dependencies when creating the project module

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Realization of commodity inquiry service

Business description

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Business timing analysis

Query all commodity information, and analyze the business time sequence, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

Commodity query method and SQL mapping are defined in goodsdao interface, and all commodity information is obtained 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 class 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);
        }
    }
}

Analysis of test results

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The URL configuration of the connection database is as follows:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • Duplicate definition of SQL mapping, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The problem of null pointer is shown in the figure

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • SQL syntax, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Definition and implementation of service interface method

Definition of goodsservice interface and commodity query method

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

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 class 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 way in unit testing)
 Assertions.assertEquals(true, goodsList.size()>0);
    }
}

Analysis of test results

  • As shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Definition and implementation of controller object method

Define the goodscontroller class, add the dogoodsui method, add the query commodity information code, store the query 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 business layer method to get commodity information
         List<Goods> list= goodsService.findGoods();
         //Store data in request scope
         model.addAttribute("list", list);
         return "goods";//viewname
    }
    
}

Design and implementation of goods list page

Add in the templates / pages directory goods.html Page, and add HTML elements to the body, and 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, and can fill the data in the server model on the page, and then implement the interaction with. Its official website is thymeleaf.org

Data presentation analysis on the goods page:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Start Tomcat for access test analysis

First, start tomcat, then open the browser, enter the access address in the address bar, get the server-side data and render it, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Bug and problem analysis during project startup and operation

  • STS console “?” symbol, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The service failed to start, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • There are no errors in the template, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The date format is incorrect, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The content of ${} on the page is wrong, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • The page date format is incorrect, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • Dependency injection failed, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • Null pointer exception, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Product deletion business implementation

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:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Business timing analysis

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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 the delete method in the goodsservice interface. The code is as follows:

int deleteById(Integer id);

Add the deletebyid method implementation to the goodsserviceimpl implementation class. 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";
    } 

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

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

The official application description of thymeleaf is shown in the figure

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

In the deletion operation, the code Association description between the client and the server is shown in the figure

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Start Tomcat server for access test analysis

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Bug and problem analysis in the process of project startup and operation

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Realization of commodity addition business

Business description

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Business timing analysis

On the product adding page, enter the product information, and then submit it to the server for saving. The timing analysis is shown in the figure
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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, SQL can also be defined in 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 to the goodsservceimpl 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 the goodscontroller class to handle the product addition request. The code is as follows:

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

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

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

Design and implementation of goods add page

Add goods to the pages directory of templates- add.html Page, code 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>

stay goods.html Hyperlinks can jump to the add page. The key codes are as follows:

< a th: HTML "@ {/ goods / dogoodsaddui}" > add 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 type in the addresshttp://localhost/goods/doGood…)The following interface appears, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Step 3: fill in the form in the add page, and then click the Save button to submit the form data to the server, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module
Step 4: add the form data submission process analysis in the page, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Bug and problem analysis in the process of project startup and operation

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

  • Database integrity constraint exception, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Implementation of commodity modification business

Business description

On the product list page, click the update option, query the current line record based on the product ID, and then update it to the goods update page, as shown in the figure:
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module
Select in the update page, modify the product information, and then click Update goods to submit the form data to the server for update

Business timing analysis

Timing design of commodity information query based on ID
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module
Submit the data in the goods update page to the server for update timing design
07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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);

Add the method and SQL mapping for updating goods based on ID in goodsdao. 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 the method of querying and updating commodity information based on ID in goodsservice. The code is as follows:

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

In the product information and serviceimpl, the query method 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 the method of querying 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 the product code in goodscontroller as follows:

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

Design and implementation of goods modification page

Add goods to the templates directory- update.html Page, code design 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 visit the product list page, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Bug and problem analysis in the process of project startup and operation

  • Page design analysis, as shown in the figure:

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

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

07 springboot + mybatis + spring technology integration to realize crud operation of commodity module

Summary

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