首页 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
    suffix: .html
    prefix: classpath:/templates/
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>美国职业篮球联盟(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 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="控球后卫"/>控球后卫
      <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>修改球员信息</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实现增删改查功能

然后点击保存 添加成功后跳转到idnex.html并显示数据

SpringBoot怎么整合Mybatis与thymleft实现增删改查功能

前端数据显示表面成功添加

点击修改 根据findById方法找到数据,并跳转到update.htnl页面进行显示

SpringBoot怎么整合Mybatis与thymleft实现增删改查功能

我们修改所属球队为 奇才队 点击保存

SpringBoot怎么整合Mybatis与thymleft实现增删改查功能

跳转到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