SpringBoot整合MyBatis项目进行CRUD操作项目示例

文章目录

  • SpringBoot整合MyBatis项目进行CRUD操作项目示例
    • 1.1.需求分析
    • 1.2.创建工程
    • 1.3.pom.xml
    • 1.4.application.properties
    • 1.5.启动类
  • 2.添加用户
    • 2.1.数据表设计
    • 2.2.pojo
    • 2.3.mapper
    • 2.4.service
    • 2.5.junit
    • 2.6.controller
    • 2.7.thymeleaf
    • 2.8.测试
  • 3.查询用户
    • 3.1.mapper
    • 3.2.service
    • 3.4.controller
    • 3.5.thymeleaf
    • 3.6.测试
  • 4.用户登录
    • 4.1.mapper
    • 4.2.service
    • 4.4.controller
    • 4.5.thymeleaf
    • 4.6.测试
  • 5.SpringBoot整合日期转换器
    • 5.1.添加日期转换器
    • 5.2.配置日期转换器
  • 6.SpringBoot整合拦截器
    • 6.1.添加拦截器
    • 6.2.配置拦截器

SpringBoot整合MyBatis项目进行CRUD操作项目示例

1.1.需求分析

通过使用 SpringBoot+MyBatis整合实现一个对数据库中的 users 表的 CRUD

1.2.创建工程

04_springboot_mybatis

1.3.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version></parent><groupId>com.by</groupId><artifactId>04_springboot_mybatis</artifactId><version>1.0-SNAPSHOT</version><properties><java.version>1.8</java.version></properties><dependencies><!-- springBoot 的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Mybatis 启动器 --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><!-- mysql 数据库驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!-- druid 数据库连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><!-- 添加 junit 环境的 jar 包 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.0</version></dependency></dependencies>
</project>

1.4.application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=1111
spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcemybatis.type-aliases-package=com.by.pojologging.level.com.by.mapper=DEBUG

1.5.启动类

@SpringBootApplication
@MapperScan("com.by.mapper") // @MapperScan 用户扫描MyBatis的Mapper接口
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}

2.添加用户

2.1.数据表设计

CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`nam` varchar(255) DEFAULT NULL,`sex` int(11) DEFAULT NULL,`pwd` varchar(255) DEFAULT NULL,`birth` datetime DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

2.2.pojo

public class User {private Integer id;private String nam;private String pwd;private Integer sex;private Date birth;
}

2.3.mapper

public interface UserMapper {public void insertUser(User user);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.UserMapper"><insert id="insertUser" parameterType="user">insert into user(nam,pwd,sex,birth) values(#{nam},#{pwd},#{sex},#{birth})</insert>
</mapper>

2.4.service

@Service
@Transactional
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic void addUser(User user) {this.userMapper.insertUser(user);}
}

2.5.junit

/***  main方法:*		ApplicationContext ac=new *       			ClassPathXmlApplicationContext("classpath:applicationContext.xml");*  junit与spring整合:*      @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合*   	@Contextconfiguartion("classpath:applicationContext.xml")  *  junit与SpringBoot整合: *		@RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合*		@SpringBootTest(classes={App.class}):加载SpringBoot启动类。启动springBoot*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class UserServiceTest {@Autowiredprivate UserService userService;@Testpublic void testAddUser(){User user = new User();user.setId(1);user.setNam("二狗");user.setPwd("111");user.setSex(1);user.setBirth(new Date());this.userService.addUser(user);}
}

2.6.controller

@Controller
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;/*** 页面跳转*/@RequestMapping("/{page}")public String showPage(@PathVariable String page) {return page;}/*** 添加用户*/@RequestMapping("/addUser")public String addUser(User user) {this.userService.addUser(user);return "ok";}
}

2.7.thymeleaf

add.html

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>添加用户</title>
</head>
<body>
<h3>新增用户</h3>
<hr/>
<form th:action="@{/user/addUser}" method="post">姓名:<input type="text" name="nam"/><br/>密码:<input type="text" name="pwd"/><br/>性别:<input type="radio" name="sex" value="1"/><input type="radio" name="sex" value="0"/><br/>生日:<input type="text" name="birth"/><br/><input type="submit" value="确定"/><br/>
</form>
</body>
</html>

2.8.测试

在这里插入图片描述

3.查询用户

3.1.mapper

public List<User> listUser();
<select id="listUser" resultType="user">select * from user
</select>

3.2.service

	@Overridepublic List<User> listUser() {return userMapper.listUser();}

3.4.controller

	/*** 查询全部用户*/@RequestMapping("/listUser")public String listUser(Model model) {List<User> list = this.userService.listUser();model.addAttribute("list", list);return "list";}

3.5.thymeleaf

list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>首页</title><style type="text/css">table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}table, th, td {border: 1px solid darkslategray;padding: 10px}</style>
</head>
<body>
<div style="text-align: center"><span style="color: darkslategray; font-size: 30px">欢迎光临!</span><hr/><table class="list"><tr><th>id</th><th>姓名</th><th>密码</th><th>性别</th><th>生日</th></tr><tr th:each="user : ${list}"><td th:text="${user.id}"></td><td th:text="${user.nam}"></td><td th:text="${user.pwd}"></td><td th:text="${user.sex==1}?'男':'女'"></td><td th:text="${#dates.format(user.birth,'yyyy-MM-dd')}"></td></tr></table>
</div>
</body>
</html>

3.6.测试

在这里插入图片描述

4.用户登录

4.1.mapper

public Users login(User user);
	<select id="login" parameterType="User" resultType="User">select * from user where nam=#{nam} and pwd=#{pwd}</select>

4.2.service

	@Overridepublic Users login(User user) {return userMapper.login(user);}

4.4.controller

	@RequestMapping("/login")public String login(Model model, User user, HttpSession session) {User loginUser = usersService.login(user);if(user!=null){session.setAttribute("loginUser", loginUser);return "redirect:/user/listUser";}return "login";}

添加PageController

@Controller
public class PageController {@RequestMapping("/")public String showLogin(){return "login";}
}

4.5.thymeleaf

login.html

<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<center><h3>登录</h3><hr/><form th:action="@{/user/login}" method="post">账号:<input type="text" name="nam"/><br/>密码:<input type="text" name="pwd"/><br/><input type="submit" value="确定"/><br/></form>
</center>
</body>
</html>

4.6.测试

在这里插入图片描述

5.SpringBoot整合日期转换器

5.1.添加日期转换器

import java.text.ParseException;
import java.util.Date;import org.springframework.core.convert.converter.Converter;
import org.apache.commons.lang3.time.DateUtils;
public class DateConverter implements Converter<String, Date>{@Overridepublic Date convert(String str) {String[] patterns = new String[]{"yyyy-MM-dd","yyyy-MM-dd hh:mm:ss","yyyy/MM/dd","yyyy/MM/dd hh:mm:ss","MM-dd-yyyy","dd-MM-yyyy"};try {Date date = DateUtils.parseDate(str, patterns);return date;} catch (ParseException e) {e.printStackTrace();}return null;}}

5.2.配置日期转换器

  • 说明

    WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式针对框架进行个性化定制,例如:拦截器,类型转化器等等。

  • 代码示例

    import com.by.converter.DateConverter;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.format.FormatterRegistry;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Component
    public class MyConfig implements WebMvcConfigurer {@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(new DateConverter());}}
    

6.SpringBoot整合拦截器

6.1.添加拦截器

package com.by.interceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.by.pojo.Users;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;public class LoginInterceptor implements HandlerInterceptor{@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception {Users user = (Users) request.getSession().getAttribute("user");if(user!=null){return true;}response.sendRedirect("/");return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {}}

6.2.配置拦截器

修改MyConfig

	//<mvc:interceptors>@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/emp/**");}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/631387.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【用法总结】LiveData组件要点

【用法总结】LiveData组件要点 1、如何实现和生命周期的关联&#xff1f;1.1 observe的实现逻辑&#xff1a;1.2 观察者的装饰者&#xff1a;ObserverWrapper1.3 观察者集合的存储&#xff1a;SafeIterableMap<Observer<? super T>, ObserverWrapper>&#xff0c;…

Linux第30步_通过USB OTG将固件烧写到eMMC中

学习目的&#xff1a;在Win11中&#xff0c;使用STM32CubeProgrammer工具&#xff0c;通过USB OTG将固件烧写到eMMC中。 安装软件检查&#xff1a; 1、是否安装了JAVA; 2、是否安装了STM32CubeProgrammer工具; 3、是否安装 了DFU驱动程序; 4、是否安装了“Notepad”软件; …

机器学习之卷积神经网络

卷积神经网络是一类包含卷积计算且具有深度结构的前馈神经网络,是深度学习的代表算法之一。卷积神经网络具有表征学习能力,能够按其阶层结构对输入信息进行平移不变分类,因此又称为SIANN。卷积神经网络仿照生物的视知觉机制构建,可以进行监督学习和非监督学习,其隐含层内的…

Verilog刷题笔记16

题目&#xff1a; Since digital circuits are composed of logic gates connected with wires, any circuit can be expressed as some combination of modules and assign statements. However, sometimes this is not the most convenient way to describe the circuit. Pro…

嵌入式软件工程师面试题——2025校招社招通用(二十一)

说明&#xff1a; 面试群&#xff0c;群号&#xff1a; 228447240面试题来源于网络书籍&#xff0c;公司题目以及博主原创或修改&#xff08;题目大部分来源于各种公司&#xff09;&#xff1b;文中很多题目&#xff0c;或许大家直接编译器写完&#xff0c;1分钟就出结果了。但…

【Java】——期末复习题库(十二)

&#x1f383;个人专栏&#xff1a; &#x1f42c; 算法设计与分析&#xff1a;算法设计与分析_IT闫的博客-CSDN博客 &#x1f433;Java基础&#xff1a;Java基础_IT闫的博客-CSDN博客 &#x1f40b;c语言&#xff1a;c语言_IT闫的博客-CSDN博客 &#x1f41f;MySQL&#xff1a…

软件开发架构

【 一 】软件开发架构图 【 1】ATM和选课系统 三层的开发架构 前段展示台 后端逻辑层 数据处理层 【二】软件开发架构的步骤流程 需求分析&#xff1a;在软件开发架构设计之前&#xff0c;需要对应用系统进行需求分析&#xff0c;明确用户需求、功能模块、业务流程等内容。…

CSS Day10

10.1 2D位移 属性名&#xff1a;transform 属性值&#xff1a;translateX 水平方向的位移 相对于自身位置移动 translateY 垂直方向的位移 相对于自身位置移动 transform&#xff1a;translate(x,y); 位移和定位搭配使用&#xff1a; position:absolute; top:50%; left:50%; tr…

LeetCode881. Boats to Save People

文章目录 一、题目二、题解 一、题目 You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, p…

flask 与小程序 菜品详情和分享功能

mina/pages/food/info.wxml <import src"../../wxParse/wxParse.wxml" /> <view class"container"> <!--商品轮播图--> <view class"swiper-container"><swiper class"swiper_box" autoplay"{{autop…

基于springboot+vue的校园管理系统(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 项目背景…

npm install 无反应 npm run serve 无反应

说明情况&#xff1a;其实最开始我就是发现我跟着黑马的苍穹外卖的前端day2的环境搭建做的时候&#xff0c;到这一步出现了问题&#xff0c;无论我怎么 npm install 和 npm run serve 都没有像黑马一样有很多东西进行加载&#xff0c;因此我换了一种方法 1.在这个文件夹下cmd …

Cmake 中list命令总结

Cmake 中list命令总结 获取list的长度 list(LENGTH <list> <output variable>) # LENGTH: 子命令LENGTH用于读取列表长度 # <list>&#xff1a;当前操作的列表 # <output variable>&#xff1a;新创建的变量&#xff0c;用于存储列表的长度&#xff…

docker使用指南疑难杂症

使用指南 一 常见命令 二 非常见情况 1 构建包不成功留下一堆废镜像和容器<none>如何清理&#xff1f; https://blog.csdn.net/catoop/article/details/91908719 2 docker0 ip没了怎么办&#xff1f; 容器stop&#xff08;不确定是否必须&#xff0c;关上保险&…

【Qt5】QString的成员函数arg

2024年1月16日&#xff0c;周二上午 函数的功能 当你使用QString的arg函数时&#xff0c;你可以将变量插入到字符串中&#xff0c;从而动态地构建字符串。 函数的语法格式 这个函数的一般形式是&#xff1a; QString QString::arg(const QString &a, int fieldWidth 0…

63.Spring事务的失效原因?

63.Spring事务的失效原因&#xff1f; 数据库引擎不支持事务&#xff1a;某些数据库引擎可能不支持事务操作&#xff0c;或者配置不正确&#xff0c;导致无法使用事务功能。 (1)、这里以 MySQL 为例&#xff0c;其 MyISAM 引擎是不支持事务操作的&#xff0c;InnoDB 才是支持事…

2024年1月【ORACLE战报】| 新年第一波OCP证书来了!

相关文章&#xff1a; 2023年12月【考试战报】|ORACLE OCP 19C考试通过 2023年10月【考试战报】|ORACLE OCP 19C考试通过 2023.7月最新OCP考试通过|微思-ORACLE官方授权中心 OCP 19C题库稳定&#xff01;https://download.csdn.net/download/XMWS_IT/88309681?ops_request_…

Js面试之数据类型相关

Js之数据类型 都有哪些数据类型&#xff1f;不同数据类型如何转换&#xff1f;数据类型检测方法有哪些&#xff1f;为什么说Js是动态数据类型&#xff1f;为什么说Js是弱类型语言&#xff1f; 最近在整理一些前端面试中经常被问到的问题&#xff0c;分为vue相关、react相关、js…

MySQL 8.0 架构 之错误日志文件(Error Log)(1)

文章目录 MySQL 8.0 架构 之错误日志文件&#xff08;Error Log&#xff09;&#xff08;1&#xff09;MySQL错误日志文件&#xff08;Error Log&#xff09;MySQL错误日志在哪里Window环境Linux环境 错误日志相关参数log_error_services 参考 【声明】文章仅供学习交流&#x…

【昕宝爸爸小模块】深入浅出之POI是如何做大文件的写入的

➡️博客首页 https://blog.csdn.net/Java_Yangxiaoyuan 欢迎优秀的你&#x1f44d;点赞、&#x1f5c2;️收藏、加❤️关注哦。 本文章CSDN首发&#xff0c;欢迎转载&#xff0c;要注明出处哦&#xff01; 先感谢优秀的你能认真的看完本文&…