Home  >  Article  >  Java  >  How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

王林
王林forward
2023-05-11 16:19:061453browse

First we create the project. Note: When creating the SpringBoot project, you must be connected to the Internet otherwise an error will be reported.

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

After the project is created, we first Compile application.yml

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

#Specify port number
server:
port: 8888
#Configure mysql data source
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/nba?serverTimezone=Asia/Shanghai
username: root
password: root
#Configure template engine thymeleaf
thymeleaf:
mode: HTML5
cache: false
suffix: .html
prefix: classpath:/templates /
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.bdqn.springboot #Put the package name

Note: There must be a space after:. This is its syntax. If there is no space, an error will be reported when running.

Next, we will build the project and create the following packages. You can create other tool packages according to your actual needs. Class

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

mapper: used to store dao layer interface

pojo: used to store entity classes

service: used to store service Layer interface, and service layer implementation class

web: used to store the controller control layer

Next we start writing code

The first is the entity class, today we are doing one Simple addition, deletion, modification and query of two tables

package com.baqn.springboot.pojo;
import lombok.Data;
@Data
public class Clubs {
    private int cid;
    private String cname;
    private String city;
}
package com.baqn.springboot.pojo;
import lombok.Data;
@Data
public class Players {
    private int pid;
    private String pname;
    private String birthday;
    private int height;
    private int weight;
    private String position;
    private int cid;
    private String cname;
    private String city;
}

Using @Data annotation can effectively reduce the amount of code in the entity class and reduce the writing of get/set and toString

Then the mapper layer

package com.baqn.springboot.mapper;
import com.baqn.springboot.pojo.Players;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface PlayersMapper {
    /**
     * 查询所有
     * @return
     */
    List findAll();
    /**
     * 根据ID查询
     * @return
     */
    Players findById(Integer id);
    /**
     * 新增
     * @param players
     * @return
     */
    Integer add(Players players);
    /**
     * 删除
     * @param pid
     * @return
     */
    Integer delete(Integer pid);
    /**
     * 修改
     * @param players
     * @return
     */
    Integer update(Players players);
}

After using @mapper, there is no need to set the scanning address in the spring configuration. Through the namespace attribute in mapper.xml corresponding to the relevant mapper class, spring will dynamically generate the bean and inject it into Servicelmpl.

Then the service layer

package com.baqn.springboot.service;
import com.baqn.springboot.pojo.Players;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface PlayersService {
    List findAll();
    Players findById(Integer pid);
    Integer add(Players players);
    Integer delete(Integer pid);
    Integer update(Players players);
}
package com.baqn.springboot.service;
import com.baqn.springboot.mapper.PlayersMapper;
import com.baqn.springboot.pojo.Players;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PlayersServiceImpl implements  PlayersService{
    @Autowired
    private PlayersMapper mapper;
    @Override
    public List findAll() {
        return mapper.findAll();
    }
    @Override
    public Players findById(Integer pid) {
        return mapper.findById(pid);
    }
    @Override
    public Integer add(Players players) {
        return mapper.add(players);
    }
    @Override
    public Integer delete(Integer pid) {
        return mapper.delete(pid);
    }
    @Override
    public Integer update(Players players) {
        return mapper.update(players);
    }
}

Finally the controller control class of the web layer

package com.baqn.springboot.web;
import com.baqn.springboot.pojo.Players;
import com.baqn.springboot.service.PlayersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class PlayersController {
    @Autowired
    private PlayersServiceImpl service;
    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List allList = service.findAll();
        model.addAttribute("allList",allList);
        return "index";
    }
    @RequestMapping("/findById/{pid}")
    public String findById(Model model,@PathVariable("pid") Integer pid) {
        Players list = service.findById(pid);
        //System.out.println("---------------"+list.toString());
        model.addAttribute("list",list);
        return "update.html";
    }
    @RequestMapping("/add")
    public String add(Model model, Players players){
        Integer count = service.add(players);
        if (count>0){
            return "redirect:/findAll";
        }
        return "add";
    }
    @RequestMapping("/delete/{pid}")
    public String delete(Model model,@PathVariable("pid") Integer pid){
        Integer count = service.delete(pid);
        if (count>0){
            return "redirect:/findAll";
        }
        return null;
    }
    @RequestMapping("/a1")
    public String a1(Model model, Players players){
        return "add.html";
    }
    @RequestMapping("/update")
    public String update(Model model,Players plays){
        Integer count = service.update(plays);
        if (count>0){
            return "redirect:/findAll";
        }
        return null;
    }
}

Note: The a1 method is only used to jump to the page and has no other effect. If If you have a better jump method, please leave me a message.

Now that the preparations are done, you can start writing SQL statements

mapper.xml can be written in the resources below or in In the above mapper layer

, if it is written above, you need to write a resource filter in the pom. If you are interested, you can go to Baidu





    
    
    
        INSERT INTO `nba`.`players`(pname, birthday, height, weight, position, cid)
        VALUES (#{pname}, #{birthday}, #{height}, #{weight}, #{position}, #{cid});
    
    
        delete from players where pid = #{pid}
    
    
        UPDATE `nba`.`players`
        
            pname=#{pname},
            birthday=#{birthday},
            height=#{height},
            weight=#{weight},
            position=#{position},
            cid=#{cid}
        
        WHERE `pid` = #{pid};
    

Note: The corresponding id in mapper.xml It is the method of the mapper layer interface. You must not write it wrong.

Up to now, our back-end code has been completely completed. The front-end page is as follows

Homepageindex.html



    Title

美国职业篮球联盟(NBA)球员信息

新增
球员编号 球员名称 出生时间(yyyy-MM-dd) 球员身高(cm) 球员体重(kg) 球员位置 所属球队 相关操作
${list.height} 修改 删除

New page add.html



      
      Title

新增球员

球员名称:

出生日期:

球员升高:

球员体重:

球员位置: 控球后卫 得分后卫 小前锋 大前锋 中锋

所属球队:

Modify page update.html




  
  Title

修改球员信息


球员编号:
球员姓名:
出身日期:
球员身高:
球员体重:
球员位置:
所属球队:

Database creation source code--Note: I am using MySQL database

create table clubs(
		cid int primary key auto_increment,
		cname varchar(50) not null,
		city varchar(50) not null
)
create table players(
		pid int primary key auto_increment,
		pname varchar(50) not null,
		birthday datetime not null,
		height int not null,
		weight int not null,
		position varchar(50) not null,
		cid int not null
)
alter  table  players  add  constraint  players_cid
foreign key(cid)  references  clubs(cid);
insert into clubs values
(1,'热火队','迈阿密'),
(2,'奇才队','华盛顿'),
(3,'魔术队','奥兰多'),
(4,'山猫队','夏洛特'),
(5,'老鹰队','亚特兰大')
insert into players values
(4,'多多','1989-08-08',213,186,'前锋',1),
(5,'西西','1987-10-16',199,162,'中锋',1),
(6,'南南','1990-01-23',221,184,'后锋',1)

Finally for everyone to see The following page is displayed

Enter in the address bar: http://localhost:8888/findAll Enter all query methods and then jump to idnex.html for display

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

Click Add to jump to the new page

Enter the parameters

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

Then click Save and jump to idnex.html after successful addition and display the data

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

The front-end data display surface was successfully added

Click to modify to find the data according to the findById method, and jump to the update.htnl page for display

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

We change the team to be the Wizards and click save

How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions

Jump to the index.html page and the data is successfully modified

The above is the detailed content of How SpringBoot integrates Mybatis and thymleft to implement add, delete, modify and check functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete