当前位置:

首页 > 编程开发 > SpringBoot怎么整合Mybatis与thymleft实现增删改查功能

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

首先我们先创建项目注意:创建SpringBoot项目时一定要联网不然会报错项目创建好后我们首先对application.yml进行编译#指定端口号server:port:8888#配置mysql数据源spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://localhost:3306/nba?serverTimezone=Asia/Shanghaiusername:rootpassword:root#配置模板

本文目录

    首先我们先创建项目 注意:创建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 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 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);
        }
    }

    最后是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 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里面写一个资源过滤器,有兴趣的话可以去百度

    
    
    
    
        
            select * from clubs c , players p
            where c.cid = p.cid
        
        
            select * from clubs c , players p
            where c.cid = p.cid and p.pid=#{pid}
        
        
            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};
        
    

    注意:mapper.xml中的id里对应的是mapper层接口的方法,一定不能写错

    到现在为止我们的后端代码就已经完全搞定了,前端页面如下

    主页 index.html

    
    
        Title
    
    
    
        
            

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

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

    新增页 add.html

    
    
          
          Title
    
    
    
      新增球员
      
        

          球员名称:                 

          出生日期:                 

          球员升高:                 

          球员体重:                 

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

          所属球队:                热火队         奇才队         魔术队         山猫队         老鹰队                         

    修改页 update.html

    
    
    
      
      Title
    
    
        
          

    修改球员信息

          
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    球员编号:
    球员姓名:
    出身日期:
    球员身高:
    球员体重:
    球员位置:
    所属球队:                              --请选择球队--               热火队               奇才队               魔术队               山猫队               老鹰队               
               

    数据库创建源码 -- 注意:我用的是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,'热火队','迈阿密'),
    (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)

    最后给大家看一下页面展示

    在地址栏输入: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页面并且数据成功修改

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    上一篇: springboot怎么整合mybatis实现数据库的更新批处理
    下一篇: SpringBoot怎么选择自有bean优先加载
    相关文章 更多
    MyBatis XML开发全面完整指南
    MyBatis XML开发全面完整指南

    MyBatisXML开发方式适合复杂SQL逻辑,通过配置数据库连接与mapper路径,在接口和XML映射文件中实现增删改查操作。XML支持多表查询及结果映射,#{}使用预编译防注入,${}直接拼接需注意字符串引号。

    MyBatis Mapper 接口原理与实现解析
    MyBatis Mapper 接口原理与实现解析

    MyBatis通过动态代理自动生成Mapper接口实现类,运行时将接口方法绑定到SQL语句,结合XML映射文件中的SQL与参数配置,由SqlSession执行并返回结果,避免了手动编写实现类的繁琐过程。

    MyBatis框架常见问题及解决方案
    MyBatis框架常见问题及解决方案

    MyBatis常见问题包含:1.实体类属性与数据库字段不一致,解决方案为使用@Column注解映射;2.执行更新操作失败,需要配置update元素并检查SQL语句;3.查询结果映射出错,需检查resultMap配置是否正确;4.解析SQL参数失败,要使用#{}占位符并确保参数类型匹配。

    MyBatis框架中设计模式的应用
    MyBatis框架中设计模式的应用

    MyBatis框架广泛应用设计模式,包括:工厂模式:创建SqlSessionFactory对象,管理数据库连接和查询;代理模式:实现延迟加载和懒加载,提高性能。外观模式:封装对数据库访问,简化代码维护。其中,一对多关系映射可以通过User和Order类、Mapper接口和MapperXML配置实现,使用延迟加载和嵌套resultMap优化性能。

    MyBatis 的动态 SQL 解析:原理、实现和优化
    MyBatis 的动态 SQL 解析:原理、实现和优化

    MyBatis动态SQL解析:原理:使用TAG和OGNL表达式动态构建SQL语句。实现:通过SqlNode、SqlSource和ParameterHandler接口实现。优化:避免不必要的动态SQL、优化OGNL表达式、使用PreparedStatement缓存和配置查询超时。

    springBoot项目常用目录有哪些
    springBoot项目常用目录有哪些

    springBoot项目常用目录springBoot项目的目录结构及名规范介绍基于SpringBoot开发时的目录结构及命名规范,通过介绍能够为你解决,在实际项目中如何规划目录结构?如何命名目录更规范?各个目录分别代表什么含义?等三个问题。目录说明servicex//项目名|-admin-ui//管理服务前端代码(一般将UI和SERVICE放到一个工程中,便于管理)|-servicex-auth//模块1|-servicex-common//模块2|-servicex-gateway//模块3|-serv

    正确使用MyBatis中的小于符号
    正确使用MyBatis中的小于符号

    MyBatis是一个用Java语言编写的持久层框架,广泛用于数据库操作。在MyBatis中,使用小于号(<)进行条件查询是很常见的操作。但是,小于号在MyBatis中有一些使用注意事项,本文将介绍MyBatis小于号的正确使用方法,并提供具体的代码示例。1.在MyBatis中使用小于号的基本方法在MyBatis中使用小于号进行条件查询,一般是在SQL

    解析MyBatis的缓存机制:比较一级缓存和二级缓存的使用场景
    解析MyBatis的缓存机制:比较一级缓存和二级缓存的使用场景

    MyBatis的缓存机制解析:一级缓存与二级缓存的区别与应用在MyBatis框架中,缓存是一个非常重要的特性,可以有效提升数据库操作的性能。其中,一级缓存和二级缓存是MyBatis中常用的两种缓存机制。本文将详细解析一级缓存与二级缓存的区别与应用,并提供具体的代码示例进行说明。一、一级缓存一级缓存也被称为本地缓存,它默认开启且不可关闭。一级缓存是SqlSes

    深入了解MyBatis缓存机制:揭秘缓存存储原理
    深入了解MyBatis缓存机制:揭秘缓存存储原理

    MyBatis缓存机制详解:一文读懂缓存存储原理引言在使用MyBatis进行数据库访问时,缓存是一个非常重要的机制,能够有效减少对数据库的访问,提高系统性能。本文将详细介绍MyBatis的缓存机制,包括缓存的分类、存储原理和具体的代码示例。一、缓存的分类MyBatis的缓存主要分为一级缓存和二级缓存两种。一级缓存一级缓存是SqlSession级别的缓存,当在

    详解在MyBatis中使用小于符号的方法
    详解在MyBatis中使用小于符号的方法

    MyBatis中小于号的写法详解MyBatis是一个优秀的持久层框架,广泛应用于Java开发中。在使用MyBatis进行数据库操作的过程中,我们经常会用到小于号(<)进行条件查询。但是,MyBatis中小于号的写法并不像普通的SQL语句那样直接使用小于号符号,而是需要使用特定的方式来实现。本文将详细解释MyBatis中小于号的写法,并提供具体的代码示例

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。