目錄
美国职业篮球联盟(NBA)球员信息
新增球员
修改球员信息
首頁 Java java教程 SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

May 11, 2023 pm 04:19 PM
mybatis springboot

首先我們先建立專案注意:建立SpringBoot專案時一定要連網不然會報錯

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

專案建立好後我們先對application.yml 編譯

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

# 指定連接埠號碼
server:
 port: 8888
#設定mysql資料來源
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
   tempsuffix:##    cache: false
   tempsuffix: .html#c: class.html#: class /
mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.bdqn.springboot  #放包名

## 注意:在:後一定要空格,這是他的語法,不空格就會運行報錯

接下來我們進行對項目的構建創建好如下幾個包可根據自己實際需要創建其他的工具包之類別的

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能mapper:用於存放dao層介面

pojo:用於存放實體類別

service:用於存放service層接口,以及service層實作類別

web:用來存放controller控制層

接下來我們開始寫程式碼

#首先是實體類,今天做的是一個兩個表的簡單增刪改查

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註解可以有效減少實體類別中的程式碼數量,縮減了對於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();
    /**
     * 根据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配置中設定掃描位址,透過mapper.xml裡面的namespace屬性對應相關的mapper類,spring將動態的生成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方法只是用於跳轉頁面,並沒有其他作用,如果有更好的跳轉方法可以給我留言哦

現在準備工作都做完了,可以開始寫SQL語句了

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

如果寫在上面的話需要在pom裡面寫一個資源過濾器,有興趣的話可以去百度

<?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=绑定一个对应的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裡對應的是mapper層介面的方法,一定不能寫錯

到現在為止我們的後端程式碼就已經完全搞定了,前端頁面如下

首頁index.html

<html>
<head>
    <title>Title</title>
</head>
<body>
<div align="center">
    <table border="1">
        <h2 id="美国职业篮球联盟-NBA-球员信息">美国职业篮球联盟(NBA)球员信息</h2>
        <a th:href="@{/a1}" rel="external nofollow" >新增</a>
        <tr>
            <th>球员编号</th>
            <th>球员名称</th>
            <th>出生时间(yyyy-MM-dd)</th>
            <th>球员身高(cm)</th>
            <th>球员体重(kg)</th>
            <th>球员位置</th>
            <th>所属球队</th>
            <th>相关操作</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="@{&#39;/findById/&#39;+${list.pid}}" rel="external nofollow" >修改</a>
                    <a th:href="@{&#39;/delete/&#39;+${list.pid}}" rel="external nofollow" >删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</div>
</body>
</html>
登入後複製

新增頁add.html

<!DOCTYPE html>
<html>
      <head>
      <title>Title</title>
</head>
<body>
<div align="center">
  <h4 id="新增球员">新增球员</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="控球后卫"/>控球后卫
      <input type="radio"  name="position" value="得分后卫"/>得分后卫
      <input type="radio"  name="position" value="小前锋" />小前锋
      <input type="radio"  name="position" value="大前锋" />大前锋
      <input type="radio"  name="position" value="中锋"/>中锋
    </p >
    <p>
      所属球队:
      <select name="cid">
        <option value="1">热火队</option>
        <option value="2">奇才队</option>
        <option value="3">魔术队</option>
        <option value="4">山猫队</option>
        <option value="5">老鹰队</option>
      </select>
    </p >
    <input type="submit" value="保存">
    <input type="reset" value="重置">
  </form>
</div>
</body>
</html>
登入後複製

修改頁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 id="修改球员信息">修改球员信息</h2>
      <br/>
      <form action="/update" method="get" id="form2">
        <table>
          <tr>
            <td colspan="2"></td>
          </tr>
          <tr>
            <td>球员编号:</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>所属球队:</td>
            <td>
              <select name="cid" id="cid" th:value="${list.cid}"/>
              <option value="">--请选择球队--</option>
              <option value="1">热火队</option>
              <option value="2">奇才队</option>
              <option value="3">魔术队</option>
              <option value="4">山猫队</option>
              <option value="5">老鹰队</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>
登入後複製

資料庫建立原始碼-- 注意:我用的是MySQL資料庫

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,&#39;热火队&#39;,&#39;迈阿密&#39;),
(2,&#39;奇才队&#39;,&#39;华盛顿&#39;),
(3,&#39;魔术队&#39;,&#39;奥兰多&#39;),
(4,&#39;山猫队&#39;,&#39;夏洛特&#39;),
(5,&#39;老鹰队&#39;,&#39;亚特兰大&#39;)
insert into players values
(4,&#39;多多&#39;,&#39;1989-08-08&#39;,213,186,&#39;前锋&#39;,1),
(5,&#39;西西&#39;,&#39;1987-10-16&#39;,199,162,&#39;中锋&#39;,1),
(6,&#39;南南&#39;,&#39;1990-01-23&#39;,221,184,&#39;后锋&#39;,1)
登入後複製

最後給大家看一下頁面展示

在網址列輸入:http://localhost:8888/findAll 進入查詢所有方法再跳到idnex.html顯示

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

##點選新增跳到新增頁面

輸入參數

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

然後點選儲存新增成功後跳到idnex.html並顯示資料

SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能

前端數據顯示表面成功添加

###點擊修改根據findById方法找到數據,並跳到update.htnl頁面進行顯示####### #########我們修改所屬球隊為巫師隊點擊儲存################跳到index.html頁面並且資料成功修改################跳到index.html頁面並且資料成功修改###

以上是SpringBoot怎麼整合Mybatis與thymleft實現增刪改查功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

iBatis和MyBatis:哪個比較適合你? iBatis和MyBatis:哪個比較適合你? Feb 19, 2024 pm 04:38 PM

iBatis與MyBatis:你該選擇哪一個?簡介:隨著Java語言的快速發展,許多持久化框架也應運而生。 iBatis和MyBatis是兩個備受歡迎的持久化框架,它們都提供了一個簡單而高效的資料存取解決方案。本文將介紹iBatis和MyBatis的特點和優勢,並給出一些具體的程式碼範例,幫助你選擇合適的框架。 iBatis簡介:iBatis是一個開源的持久化框架

詳解MyBatis動態SQL標籤中的Set標籤功能 詳解MyBatis動態SQL標籤中的Set標籤功能 Feb 26, 2024 pm 07:48 PM

MyBatis動態SQL標籤解讀:Set標籤用法詳解MyBatis是一個優秀的持久層框架,它提供了豐富的動態SQL標籤,可以靈活地建構資料庫操作語句。其中,Set標籤是用來產生UPDATE語句中SET子句的標籤,在更新作業中非常常用。本文將詳細解讀MyBatis中Set標籤的用法,以及透過具體的程式碼範例來示範其功能。什麼是Set標籤Set標籤用於MyBati

比較分析JPA和MyBatis的功能和性能 比較分析JPA和MyBatis的功能和性能 Feb 19, 2024 pm 05:43 PM

JPA和MyBatis:功能與效能比較分析引言:在Java開發中,持久化框架扮演著非常重要的角色。常見的持久化框架包括JPA(JavaPersistenceAPI)和MyBatis。本文將對這兩個框架的功能和效能進行比較分析,並提供具體的程式碼範例。一、功能對比:JPA:JPA是JavaEE的一部分,提供了一個物件導向的資料持久化解決方案。它透過註解或X

實作MyBatis中批次刪除操作的多種方式 實作MyBatis中批次刪除操作的多種方式 Feb 19, 2024 pm 07:31 PM

MyBatis中實現批量刪除語句的幾種方式,需要具體程式碼範例近年來,由於資料量的不斷增加,批量操作成為了資料庫操作的一個重要環節之一。在實際開發中,我們經常需要批量刪除資料庫中的記錄。本文將重點介紹在MyBatis中實作批量刪除語句的幾種方式,並提供相應的程式碼範例。使用foreach標籤實作批量刪除MyBatis提供了foreach標籤,可以方便地遍歷一個集

MyBatis批次刪除語句的使用方法詳解 MyBatis批次刪除語句的使用方法詳解 Feb 20, 2024 am 08:31 AM

MyBatis批量刪除語句的使用方法詳解,需要具體程式碼範例引言:MyBatis是一款優秀的持久層框架,提供了豐富的SQL操作功能。在實際專案開發中,經常會遇到需要大量刪除資料的情況。本文將詳細介紹MyBatis批量刪除語句的使用方法,並附上具體的程式碼範例。使用場景:在資料庫中刪除大量資料時,逐條執行刪除語句效率低。此時,可以使用MyBatis的批次刪除功能

MyBatis快取機制詳解:一文讀懂快取儲存原理 MyBatis快取機制詳解:一文讀懂快取儲存原理 Feb 23, 2024 pm 04:09 PM

MyBatis快取機制詳解:一文讀懂快取儲存原理引言在使用MyBatis進行資料庫存取時,快取是一個非常重要的機制,能夠有效減少對資料庫的訪問,提高系統效能。本文將詳細介紹MyBatis的快取機制,包括快取的分類、儲存原理和具體的程式碼範例。一、快取的分類MyBatis的快取主要分為一級快取和二級快取兩種。一級緩存一級緩存是SqlSession級別的緩存,當在

MyBatis 一級快取詳解:如何提升資料存取效率? MyBatis 一級快取詳解:如何提升資料存取效率? Feb 23, 2024 pm 08:13 PM

MyBatis一級快取詳解:如何提升資料存取效率?在開發過程中,高效率的資料存取一直是程式設計師關注的焦點之一。而對於MyBatis這樣的持久層框架而言,快取是提升資料存取效率的關鍵方法之一。 MyBatis提供了一級快取和二級快取兩種快取機制,其中一級快取是預設開啟的。本文將詳細介紹MyBatis一級快取的機制,並提供具體的程式碼範例,幫助讀者更好地理

深入理解MyBatis中的批次Insert實作原理 深入理解MyBatis中的批次Insert實作原理 Feb 21, 2024 pm 04:42 PM

MyBatis是一款流行的Java持久層框架,廣泛應用於各種Java專案。其中,批次插入是常見的操作,可以有效提升資料庫操作的效能。本文將深入探討MyBatis中批量的Insert實作原理,並結合具體的程式碼範例進行詳細解析。 MyBatis中的批次Insert在MyBatis中,批量Insert操作通常使用動態SQL來實作。透過建構一條包含多個插入值的S

See all articles