经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
SpringBoot整合Mybatis与thymleft实现增删改查功能详解
来源:jb51  时间:2022/12/5 8:48:32  对本文有异议

首先我们先创建项目 注意:创建SpringBoot项目时一定要联网不然会报错

项目创建好后我们首先对 application.yml 进行编译

#指定端口号
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  #放包名

注意:在 :后一定要空格,这是他的语法,不空格就会运行报错

接下来我们进行对项目的构建 创建好如下几个包 可根据自己实际需要创建其他的工具包之类的

mapper:用于存放dao层接口

pojo:用于存放实体类

service:用于存放service层接口,以及service层实现类

web:用于存放controller控制层

接下来我们开始编写代码

首先是实体类,今天做的是一个两表的简单增删改查

  1. package com.baqn.springboot.pojo;
  2. import lombok.Data;
  3. @Data
  4. public class Clubs {
  5. private int cid;
  6. private String cname;
  7. private String city;
  8. }
  1. package com.baqn.springboot.pojo;
  2. import lombok.Data;
  3. @Data
  4. public class Players {
  5. private int pid;
  6. private String pname;
  7. private String birthday;
  8. private int height;
  9. private int weight;
  10. private String position;
  11. private int cid;
  12. private String cname;
  13. private String city;
  14. }

使用@Data注解可以有效减少实体类中的代码数量,缩减了对于get/set和toString的编写

然后是mapper层

  1. package com.baqn.springboot.mapper;
  2. import com.baqn.springboot.pojo.Players;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Param;
  5. import org.springframework.stereotype.Repository;
  6. import java.util.List;
  7. @Mapper
  8. @Repository
  9. public interface PlayersMapper {
  10. /**
  11. * 查询所有
  12. * @return
  13. */
  14. List<Players> findAll();
  15. /**
  16. * 根据ID查询
  17. * @return
  18. */
  19. Players findById(Integer id);
  20. /**
  21. * 新增
  22. * @param players
  23. * @return
  24. */
  25. Integer add(Players players);
  26. /**
  27. * 删除
  28. * @param pid
  29. * @return
  30. */
  31. Integer delete(Integer pid);
  32. /**
  33. * 修改
  34. * @param players
  35. * @return
  36. */
  37. Integer update(Players players);
  38. }

使用@mapper后,不需要在spring配置中设置扫描地址,通过mapper.xml里面的namespace属性对应相关的mapper类,spring将动态的生成Bean后注入到Servicelmpl中。

然后是service层

  1. package com.baqn.springboot.service;
  2. import com.baqn.springboot.pojo.Players;
  3. import org.apache.ibatis.annotations.Param;
  4. import java.util.List;
  5. public interface PlayersService {
  6. List<Players> findAll();
  7. Players findById(Integer pid);
  8. Integer add(Players players);
  9. Integer delete(Integer pid);
  10. Integer update(Players players);
  11. }
  1. package com.baqn.springboot.service;
  2. import com.baqn.springboot.mapper.PlayersMapper;
  3. import com.baqn.springboot.pojo.Players;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import java.util.List;
  7. @Service
  8. public class PlayersServiceImpl implements PlayersService{
  9. @Autowired
  10. private PlayersMapper mapper;
  11. @Override
  12. public List<Players> findAll() {
  13. return mapper.findAll();
  14. }
  15. @Override
  16. public Players findById(Integer pid) {
  17. return mapper.findById(pid);
  18. }
  19. @Override
  20. public Integer add(Players players) {
  21. return mapper.add(players);
  22. }
  23. @Override
  24. public Integer delete(Integer pid) {
  25. return mapper.delete(pid);
  26. }
  27. @Override
  28. public Integer update(Players players) {
  29. return mapper.update(players);
  30. }
  31. }

最后是web层的controller控制类

  1. package com.baqn.springboot.web;
  2. import com.baqn.springboot.pojo.Players;
  3. import com.baqn.springboot.service.PlayersServiceImpl;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import java.util.List;
  10. @Controller
  11. public class PlayersController {
  12. @Autowired
  13. private PlayersServiceImpl service;
  14. @RequestMapping("/findAll")
  15. public String findAll(Model model) {
  16. List<Players> allList = service.findAll();
  17. model.addAttribute("allList",allList);
  18. return "index";
  19. }
  20. @RequestMapping("/findById/{pid}")
  21. public String findById(Model model,@PathVariable("pid") Integer pid) {
  22. Players list = service.findById(pid);
  23. //System.out.println("---------------"+list.toString());
  24. model.addAttribute("list",list);
  25. return "update.html";
  26. }
  27. @RequestMapping("/add")
  28. public String add(Model model, Players players){
  29. Integer count = service.add(players);
  30. if (count>0){
  31. return "redirect:/findAll";
  32. }
  33. return "add";
  34. }
  35. @RequestMapping("/delete/{pid}")
  36. public String delete(Model model,@PathVariable("pid") Integer pid){
  37. Integer count = service.delete(pid);
  38. if (count>0){
  39. return "redirect:/findAll";
  40. }
  41. return null;
  42. }
  43. @RequestMapping("/a1")
  44. public String a1(Model model, Players players){
  45. return "add.html";
  46. }
  47. @RequestMapping("/update")
  48. public String update(Model model,Players plays){
  49. Integer count = service.update(plays);
  50. if (count>0){
  51. return "redirect:/findAll";
  52. }
  53. return null;
  54. }
  55. }

注意:a1方法仅仅是用于跳转页面,并没有其他作用,如果有更好的跳转方法可以给我留言哦

现在准备工作都做完了,可以开始编写SQL语句了

mapper.xml可以写在下面resources里面也可以写在上面的mapper层里

如果写在上面的话需要在pom里面写一个资源过滤器,有兴趣的话可以去百度

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!--namespace=绑定一个对应的Dao/Mapper接口-->
  6. <mapper namespace="com.baqn.springboot.mapper.PlayersMapper">
  7. <select id="findAll" resultType="com.baqn.springboot.pojo.Players">
  8. select * from clubs c , players p
  9. where c.cid = p.cid
  10. </select>
  11. <select id="findById" resultType="com.baqn.springboot.pojo.Players">
  12. select * from clubs c , players p
  13. where c.cid = p.cid and p.pid=#{pid}
  14. </select>
  15. <insert id="add" parameterType="com.baqn.springboot.pojo.Players">
  16. INSERT INTO `nba`.`players`(pname, birthday, height, weight, position, cid)
  17. VALUES (#{pname}, #{birthday}, #{height}, #{weight}, #{position}, #{cid});
  18. </insert>
  19. <delete id="delete" parameterType="int">
  20. delete from players where pid = #{pid}
  21. </delete>
  22. <update id="update" parameterType="com.baqn.springboot.pojo.Players">
  23. UPDATE `nba`.`players`
  24. <set>
  25. <if test="pname != null">pname=#{pname},</if>
  26. <if test="birthday != null">birthday=#{birthday},</if>
  27. <if test="height != null">height=#{height},</if>
  28. <if test="weight != null">weight=#{weight},</if>
  29. <if test="position != null">position=#{position},</if>
  30. <if test="cid != null">cid=#{cid}</if>
  31. </set>
  32. WHERE `pid` = #{pid};
  33. </update>
  34. </mapper>

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

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

主页 index.html

  1. <html>
  2. <head>
  3. <title>Title</title>
  4. </head>
  5. <body>
  6. <div align="center">
  7. <table border="1">
  8. <h1>美国职业篮球联盟(NBA)球员信息</h1>
  9. <a th:href="@{/a1}" rel="external nofollow" >新增</a>
  10. <tr>
  11. <th>球员编号</th>
  12. <th>球员名称</th>
  13. <th>出生时间(yyyy-MM-dd)</th>
  14. <th>球员身高(cm)</th>
  15. <th>球员体重(kg)</th>
  16. <th>球员位置</th>
  17. <th>所属球队</th>
  18. <th>相关操作</th>
  19. </tr>
  20. <!--/*@thymesVar id="abc" type=""*/-->
  21. <tr th:each="list : ${allList}">
  22. <td th:text="${list.pid}"></td>
  23. <td th:text="${list.pname}"></td>
  24. <td th:text="${list.birthday}"></td>
  25. <td th:text="${list.height}">${list.height}</td>
  26. <td th:text="${list.weight}"></td>
  27. <td th:text="${list.position}"></td>
  28. <td th:text="${list.cname}"></td>
  29. <td>
  30. <a th:href="@{'/findById/'+${list.pid}}" rel="external nofollow" >修改</a>
  31. <a th:href="@{'/delete/'+${list.pid}}" rel="external nofollow" >删除</a>
  32. </td>
  33. </tr>
  34. </c:forEach>
  35. </table>
  36. </div>
  37. </body>
  38. </html>

新增页 add.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Title</title>
  5. </head>
  6. <body>
  7. <div align="center">
  8. <h3 align="center">新增球员</h3>
  9. <form action="/add">
  10. <p>
  11. 球员名称:
  12. <input name="pname" id="pname">
  13. </p >
  14. <p>
  15. 出生日期:
  16. <input name="birthday" id="birthday">
  17. </p >
  18. <p>
  19. 球员升高:
  20. <input name="height" id="height">
  21. </p >
  22. <p>
  23. 球员体重:
  24. <input name="weight" id="weight">
  25. </p >
  26. <p>
  27. 球员位置:
  28. <input type="radio" name="position" value="控球后卫"/>控球后卫
  29. <input type="radio" name="position" value="得分后卫"/>得分后卫
  30. <input type="radio" name="position" value="小前锋" />小前锋
  31. <input type="radio" name="position" value="大前锋" />大前锋
  32. <input type="radio" name="position" value="中锋"/>中锋
  33. </p >
  34. <p>
  35. 所属球队:
  36. <select name="cid">
  37. <option value="1">热火队</option>
  38. <option value="2">奇才队</option>
  39. <option value="3">魔术队</option>
  40. <option value="4">山猫队</option>
  41. <option value="5">老鹰队</option>
  42. </select>
  43. </p >
  44. <input type="submit" value="保存">
  45. <input type="reset" value="重置">
  46. </form>
  47. </div>
  48. </body>
  49. </html>

修改页 update.html

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body class="container">
  8. <div align="center">
  9. <h1>修改球员信息</h1>
  10. <br/>
  11. <form action="/update" method="get" id="form2">
  12. <table>
  13. <tr>
  14. <td colspan="2"></td>
  15. </tr>
  16. <tr>
  17. <td>球员编号:</td>
  18. <td><input type="text" name="pid"
  19. id="pid" th:value="${list.pid}"/></td>
  20. </tr>
  21. <tr>
  22. <td>球员姓名:</td>
  23. <td><input type="text" name="pname"
  24. id="pname" th:value="${list.pname}"/></td>
  25. </tr>
  26. <tr>
  27. <td>出身日期:</td>
  28. <td><input type="text" name="birthday"
  29. id="birthday" th:value="${list.birthday}"/></td>
  30. </tr>
  31. <tr>
  32. <td>球员身高:</td>
  33. <td><input type="text" name="height"
  34. id="height" th:value="${list.height}"/></td>
  35. </tr>
  36. <tr>
  37. <td>球员体重:</td>
  38. <td><input type="text" name="weight"
  39. id="weight" th:value="${list.weight}"/></td>
  40. </tr>
  41. <tr>
  42. <td>球员位置:</td>
  43. <td><input type="text" name="position"
  44. id="position" th:value="${list.position}"/></td>
  45. </tr>
  46. <tr>
  47. <td>所属球队:</td>
  48. <td>
  49. <select name="cid" id="cid" th:value="${list.cid}"/>
  50. <option value="">--请选择球队--</option>
  51. <option value="1">热火队</option>
  52. <option value="2">奇才队</option>
  53. <option value="3">魔术队</option>
  54. <option value="4">山猫队</option>
  55. <option value="5">老鹰队</option>
  56. </select></td>
  57. </tr>
  58. <tr>
  59. <td colspan="2"><input type="submit" id="btn2" value="保存"/>
  60. <input type="reset" id="wrap-clera" value="重置"/>
  61. <a th:href="@{/index.html}" rel="external nofollow" ><input type="button" id="btn1" value="返回"/></a>
  62. </td>
  63. </tr>
  64. </table>
  65. </form>
  66. </div>
  67. </body>
  68. </html>

数据库创建源码 -- 注意:我用的是MySQL数据库

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

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

在地址栏输入:http://localhost:8888/findAll 进入到查询所有方法再跳转到idnex.html进行显示

点击新增跳转到新增页面

输入参数

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

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

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

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

跳转到index.html页面并且数据成功修改

到此这篇关于SpringBoot整合Mybatis与thymleft实现增删改查功能详解的文章就介绍到这了,更多相关SpringBoot Mybatis thymleft实现增删改查内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号