溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

發(fā)布時(shí)間:2022-12-03 09:23:18 來(lái)源:億速云 閱讀:128 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能”文章能幫助大家解決問(wèn)題。

首先我們先創(chuàng)建項(xiàng)目 注意:創(chuàng)建SpringBoot項(xiàng)目時(shí)一定要聯(lián)網(wǎng)不然會(huì)報(bào)錯(cuò)

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

項(xiàng)目創(chuàng)建好后我們首先對(duì) application.yml 進(jìn)行編譯

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

#指定端口號(hào)
server:
 port: 8888
#配置mysql數(shù)據(jù)源
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/nba?serverTimezone=Asia/Shanghai
    username: root
    password: root
#配置模板引擎 thymeleaf
  thymeleaf:
    mode: HTML5
    cache: false
    suffix: .html
    prefix: classpath:/templates/
mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.bdqn.springboot  #放包名

注意:在 :后一定要空格,這是他的語(yǔ)法,不空格就會(huì)運(yùn)行報(bào)錯(cuò)

接下來(lái)我們進(jìn)行對(duì)項(xiàng)目的構(gòu)建 創(chuàng)建好如下幾個(gè)包 可根據(jù)自己實(shí)際需要?jiǎng)?chuàng)建其他的工具包之類的

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

mapper:用于存放dao層接口

pojo:用于存放實(shí)體類

service:用于存放service層接口,以及service層實(shí)現(xiàn)類

web:用于存放controller控制層

接下來(lái)我們開始編寫代碼

首先是實(shí)體類,今天做的是一個(gè)兩表的簡(jiǎn)單增刪改查

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

使用@Data注解可以有效減少實(shí)體類中的代碼數(shù)量,縮減了對(duì)于get/set和toString的編寫

然后是mapper層

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<Players> findAll();
    /**
     * 根據(jù)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);
}

使用@mapper后,不需要在spring配置中設(shè)置掃描地址,通過(guò)mapper.xml里面的namespace屬性對(duì)應(yīng)相關(guān)的mapper類,spring將動(dòng)態(tài)的生成Bean后注入到Servicelmpl中。

然后是service層

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

最后是web層的controller控制類

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<Players> 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;
    }
}

注意:a1方法僅僅是用于跳轉(zhuǎn)頁(yè)面,并沒有其他作用,如果有更好的跳轉(zhuǎn)方法可以給我留言哦

現(xiàn)在準(zhǔn)備工作都做完了,可以開始編寫SQL語(yǔ)句了

mapper.xml可以寫在下面resources里面也可以寫在上面的mapper層里

如果寫在上面的話需要在pom里面寫一個(gè)資源過(guò)濾器,有興趣的話可以去百度

<?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">
<!--namespace=綁定一個(gè)對(duì)應(yīng)的Dao/Mapper接口-->
<mapper namespace="com.baqn.springboot.mapper.PlayersMapper">
    <select id="findAll" resultType="com.baqn.springboot.pojo.Players">
        select * from clubs c , players p
        where c.cid = p.cid
    </select>
    <select id="findById" resultType="com.baqn.springboot.pojo.Players">
        select * from clubs c , players p
        where c.cid = p.cid and p.pid=#{pid}
    </select>
    <insert id="add" parameterType="com.baqn.springboot.pojo.Players">
        INSERT INTO `nba`.`players`(pname, birthday, height, weight, position, cid)
        VALUES (#{pname}, #{birthday}, #{height}, #{weight}, #{position}, #{cid});
    </insert>
    <delete id="delete" parameterType="int">
        delete from players where pid = #{pid}
    </delete>
    <update id="update" parameterType="com.baqn.springboot.pojo.Players">
        UPDATE `nba`.`players`
        <set>
            <if test="pname != null">pname=#{pname},</if>
            <if test="birthday != null">birthday=#{birthday},</if>
            <if test="height != null">height=#{height},</if>
            <if test="weight != null">weight=#{weight},</if>
            <if test="position != null">position=#{position},</if>
            <if test="cid != null">cid=#{cid}</if>
        </set>
        WHERE `pid` = #{pid};
    </update>
</mapper>

注意:mapper.xml中的id里對(duì)應(yīng)的是mapper層接口的方法,一定不能寫錯(cuò)

到現(xiàn)在為止我們的后端代碼就已經(jīng)完全搞定了,前端頁(yè)面如下

主頁(yè) index.html

<html>
<head>
    <title>Title</title>
</head>
<body>
<div align="center">
    <table border="1">
        <h2>美國(guó)職業(yè)籃球聯(lián)盟(NBA)球員信息</h2>
        <a th:href="@{/a1}" rel="external nofollow" >新增</a>
        <tr>
            <th>球員編號(hào)</th>
            <th>球員名稱</th>
            <th>出生時(shí)間(yyyy-MM-dd)</th>
            <th>球員身高(cm)</th>
            <th>球員體重(kg)</th>
            <th>球員位置</th>
            <th>所屬球隊(duì)</th>
            <th>相關(guān)操作</th>
        </tr>
        <!--/*@thymesVar id="abc" type=""*/-->
        <tr th:each="list : ${allList}">
                <td th:text="${list.pid}"></td>
                <td th:text="${list.pname}"></td>
                <td th:text="${list.birthday}"></td>
                <td th:text="${list.height}">${list.height}</td>
                <td th:text="${list.weight}"></td>
                <td th:text="${list.position}"></td>
                <td th:text="${list.cname}"></td>
                <td>
                    <a th:href="@{'/findById/'+${list.pid}}" rel="external nofollow" >修改</a>
                    <a th:href="@{'/delete/'+${list.pid}}" rel="external nofollow" >刪除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</div>
</body>
</html>

新增頁(yè) add.html

<!DOCTYPE html>
<html>
      <head>
      <title>Title</title>
</head>
<body>
<div align="center">
  <h4 align="center">新增球員</h4>
  <form action="/add">
    <p>
      球員名稱:
      <input name="pname" id="pname">
    </p >
    <p>
      出生日期:
      <input name="birthday" id="birthday">
    </p >
    <p>
      球員升高:
      <input name="height" id="height">
    </p >
    <p>
      球員體重:
      <input name="weight" id="weight">
    </p >
    <p>
      球員位置:
      <input type="radio"  name="position" value="控球后衛(wèi)"/>控球后衛(wèi)
      <input type="radio"  name="position" value="得分后衛(wèi)"/>得分后衛(wèi)
      <input type="radio"  name="position" value="小前鋒" />小前鋒
      <input type="radio"  name="position" value="大前鋒" />大前鋒
      <input type="radio"  name="position" value="中鋒"/>中鋒
    </p >
    <p>
      所屬球隊(duì):
      <select name="cid">
        <option value="1">熱火隊(duì)</option>
        <option value="2">奇才隊(duì)</option>
        <option value="3">魔術(shù)隊(duì)</option>
        <option value="4">山貓隊(duì)</option>
        <option value="5">老鷹隊(duì)</option>
      </select>
    </p >
    <input type="submit" value="保存">
    <input type="reset" value="重置">
  </form>
</div>
</body>
</html>

修改頁(yè) update.html

<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body class="container">
    <div align="center">
      <h2>修改球員信息</h2>
      <br/>
      <form action="/update" method="get" id="form2">
        <table>
          <tr>
            <td colspan="2"></td>
          </tr>
          <tr>
            <td>球員編號(hào):</td>
            <td><input type="text" name="pid"
                                    id="pid" th:value="${list.pid}"/></td>
          </tr>
          <tr>
            <td>球員姓名:</td>
            <td><input type="text" name="pname"
                                    id="pname" th:value="${list.pname}"/></td>
          </tr>
          <tr>
            <td>出身日期:</td>
            <td><input type="text" name="birthday"
                                    id="birthday" th:value="${list.birthday}"/></td>
          </tr>
          <tr>
            <td>球員身高:</td>
            <td><input type="text" name="height"
                                    id="height" th:value="${list.height}"/></td>
          </tr>
          <tr>
            <td>球員體重:</td>
            <td><input type="text" name="weight"
                                    id="weight" th:value="${list.weight}"/></td>
          </tr>
          <tr>
            <td>球員位置:</td>
            <td><input type="text" name="position"
                                    id="position" th:value="${list.position}"/></td>
          </tr>
          <tr>
            <td>所屬球隊(duì):</td>
            <td>
              <select name="cid" id="cid" th:value="${list.cid}"/>
              <option value="">--請(qǐng)選擇球隊(duì)--</option>
              <option value="1">熱火隊(duì)</option>
              <option value="2">奇才隊(duì)</option>
              <option value="3">魔術(shù)隊(duì)</option>
              <option value="4">山貓隊(duì)</option>
              <option value="5">老鷹隊(duì)</option>
              </select></td>
          </tr>
          <tr>
            <td colspan="2"><input type="submit" id="btn2" value="保存"/>
              <input type="reset" id="wrap-clera" value="重置"/>
              <a th:href="@{/index.html}" rel="external nofollow" ><input type="button" id="btn1" value="返回"/></a>
            </td>
          </tr>
        </table>
      </form>
    </div>
</body>
</html>

數(shù)據(jù)庫(kù)創(chuàng)建源碼 -- 注意:我用的是MySQL數(shù)據(jù)庫(kù)

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,'熱火隊(duì)','邁阿密'),
(2,'奇才隊(duì)','華盛頓'),
(3,'魔術(shù)隊(duì)','奧蘭多'),
(4,'山貓隊(duì)','夏洛特'),
(5,'老鷹隊(duì)','亞特蘭大')
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)

最后給大家看一下頁(yè)面展示

在地址欄輸入:http://localhost:8888/findAll 進(jìn)入到查詢所有方法再跳轉(zhuǎn)到idnex.html進(jìn)行顯示

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

點(diǎn)擊新增跳轉(zhuǎn)到新增頁(yè)面

輸入?yún)?shù)

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

然后點(diǎn)擊保存 添加成功后跳轉(zhuǎn)到idnex.html并顯示數(shù)據(jù)

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

前端數(shù)據(jù)顯示表面成功添加

點(diǎn)擊修改 根據(jù)findById方法找到數(shù)據(jù),并跳轉(zhuǎn)到update.htnl頁(yè)面進(jìn)行顯示

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

我們修改所屬球隊(duì)為 奇才隊(duì) 點(diǎn)擊保存

SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能

跳轉(zhuǎn)到index.html頁(yè)面并且數(shù)據(jù)成功修改

關(guān)于“SpringBoot怎么整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI