Springboot+MybatisPlus入门案例(postman测试)

embedded/2024/12/22 19:55:58/

 一、项目框架

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><groupId>cn.yh</groupId><artifactId>yh-mp-springboot</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.10.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--简化代码的工具包,针对实体类--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--mybatis‐plus的springboot支持--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.0</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency></dependencies></project>

config包-分页插件配置文件

MybatisPlusConfig
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig {/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
}

controller层

package org.example.controller;import org.example.pojo.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/addUser")public void addUser(@RequestBody User user) {userService.addUser(user);}@DeleteMapping("/deleteUserById/{id}")public void deleteUserById(@PathVariable Long id) {userService.deleteUserById(id);}@PutMapping("/updateUser")public void updateUser(@RequestBody User user) {userService.updateUser(user);}@GetMapping("/getUserById")public User getUserById(@RequestParam Long id) {return userService.getUserById(id);}@GetMapping("/getAllUser")public List<User> getAllUser() {return userService.getAllUser();}@PostMapping("/addUserList")public void addUserList(@RequestBody List<User> users) {userService.addUserList(users);}
}

Mapper层

UserMapper
public interface UserMapper extends BaseMapper<User> {User myFindUserById(Integer id); //自定义的查询方法,目的是练习传统Mybatis的使用
}

Pojo实体类

User
package org.example.pojo;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.time.LocalDateTime;@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_user")   //指定数据库表
public class User {/*** 指定主键* <p>* 使用该主键生成策略:@TableId(value = "id",type = IdType.ID_WORKER) 要注意下面内容* 如果数据库id字段是bigint类型,那么java实体类中属性类型为java.long.Long,Integer位数远远不够了*/@TableId(value = "id")private Long id;//    @TableField("user_name")   //mybatis-plus默认开启驼峰匹配,可不写@TableField("user_name")private String userName;//    @TableField("password")private String password;//    @TableField("age")private Integer age;//    @TableField("birthday")private LocalDateTime birthday; //数据库中日期类型为datetime没有时分秒}

service层

UserService

package org.example.service;import org.example.pojo.User;import java.util.List;public interface UserService {void addUser(User user);void deleteUserById(Long id);void updateUser(User user);User getUserById(Long id);List<User> getAllUser();void addUserList(List<User> users);}

UserService实现类UserServiceImp

package org.example.service;import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImp implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic void addUser(User user) {userMapper.insert(user);}@Overridepublic void deleteUserById(Long id) {userMapper.deleteById(id);}@Overridepublic void updateUser(User user) {userMapper.updateById(user);}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic List<User> getAllUser() {return userMapper.selectList(null);}@Overridepublic void addUserList(List<User> users) {for (User user : users) {userMapper.insert(user);}}
}

引导类/启动类

Application 
@MapperScan("org.example.mapper") 扫描对应包下的接口并加到Spring的Ioc容器中。
package org.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("org.example.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

resources配置

UserMapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace是mapper层对应的接口名-->
<mapper namespace="org.example.mapper.UserMapper"><!--id是mapper层对应的接口名中对应的方法名--><select id="myFindUserById" resultType="User">select *from tb_userwhere id = #{id}</select></mapper>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--设置驼峰匹配,MybatisPlus默认开启驼峰匹配-->
<!--    <settings>-->
<!--        <setting name="mapUnderscoreToCamelCase" value="true"/>-->
<!--    </settings>--></configuration>
application.yml
server:port: 8082 #指定端口号
spring:application: #服务名name: local-mp#数据源,连接自己电脑上的数据库datasource:driver-class-name: com.mysql.cj.jdbc.Driver   #MySQL8版本及以上要加cj,此工程用的是MySQL8username: rootpassword: "123456"       #注意url有问题时可以尝试加时区,url中的test为数据库名url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true#日志
logging:level:root: debug#设置mybatis-plus
mybatis-plus:config-location: classpath:mybatis/mybatis-config.xml  #配置文件mapper-locations: classpath:mybatis/mapper/*.xml  #设置mapper层对应的接口对应的mapper.xml的路径type-aliases-package: org.example.pojo  #设置别名,mapper.xml中resultType="cn.yh.mp.pojo.User"可省去包,即resultType="User"#开启自动驼峰映射,注意:配置configuration.map-underscore-to-camel-case则不能配置config-location,可写到mybatis-config.xml中
#  configuration:
#    map-underscore-to-camel-case: true

二、Sql

/*Navicat Premium Data TransferSource Server         : localhostSource Server Type    : MySQLSource Server Version : 80033 (8.0.33)Source Host           : localhost:3306Source Schema         : testTarget Server Type    : MySQLTarget Server Version : 80033 (8.0.33)File Encoding         : 65001Date: 30/04/2024 00:23:33
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (`id` bigint NOT NULL AUTO_INCREMENT,`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`age` int NULL DEFAULT NULL,`birthday` datetime NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1784973424016379907 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1784972199497822210, 'jack', '123', 25, '2024-04-29 00:00:00');
INSERT INTO `tb_user` VALUES (1784972897228660738, 'tom', '123', 24, '2024-04-29 00:00:00');
INSERT INTO `tb_user` VALUES (1784973068603641857, '优雅修改', 'password2', 30, '2024-04-29 00:00:00');SET FOREIGN_KEY_CHECKS = 1;

三、Postman准备

postman准备

以person举例,在本项目中为user,步骤都一样,名字不同而已。

创建-Collections

创建请求-Request

请求介绍

1 新增:

请求方式:Post 请求路径:http://localhost:8082/user/addUser

传递数据:

  {"userName": "tom2","password": "123","age": 24,"birthday": "2024-04-29T15:59:26.302"}

2 删除:

请求方式:DELETE 请求路径:http://localhost:8082/user/deleteUserById/1784972199497822210

3 修改:

请求方式:Put 请求路径:http://localhost:8082/user/updateUser

  {"id": 1784973068603641857,"userName": "优雅修改","password": "password2","age": 30,"birthday": "2024-04-29T15:59:26.302"}

4 查询:

请求方式:Get 请求路径:http://localhost:8082/user/getUserById?id=1784972897228660738

四、测试类

不想通过postman测试的,也可以在Test包中创建测试类自测(单元测试),测试类自测不通过controller及service。

MapperPlusTest
import cn.yh.mp.mapper.UserMapper;
import cn.yh.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Arrays;
import java.util.List;@SpringBootTest
@RunWith(SpringRunner.class)
public class MapperPlusTest {@Autowiredprivate UserMapper userMapper;@Testpublic void selectAll() {List<User> users = userMapper.selectList(null);for (User user : users) {System.out.println(user);}}@Testpublic void findUserById() {User user = userMapper.myFindUserById(2);System.out.println(user);}/*** 插入数据*/@Testpublic void testInsert() {User user = new User();user.setAge(20);user.setEmail("test@yh.cn");user.setName("曹操");user.setUserName("caocao");user.setPassword("123456");userMapper.insert(user);}/*** 根据id 批量删除*/@Testpublic void testDeleteByIds() {
//根据id集合批量删除   DELETE FROM tb_user WHERE ID IN ( ? , ? , ? )int result = this.userMapper.deleteBatchIds(Arrays.asList(1, 2, 4));System.out.println("result   = " + result);}/*** 分页*/@Testpublic void testPage() {QueryWrapper<User> wrapper = new QueryWrapper<User>();wrapper.eq("age", 20); //查询条件,age=20IPage<User> page = new Page<>(1, 2);IPage<User> userIPage = userMapper.selectPage(page, wrapper);System.out.println("数据总条数:" + userIPage.getTotal());System.out.println("总页数:" + userIPage.getPages());}/*** 修改*/@Testpublic void testUpdate() {User user = new User();user.setId(5L);user.setAge(20);user.setEmail("test@yh.cn");user.setName("曹操");user.setUserName("caocao");user.setPassword("123");userMapper.updateById(user);//        userMapper.update()}/*** 模糊查询*/@Testpublic void testLike() {LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(User::getName, "曹");   //%曹%wrapper.likeRight(User::getName, "曹");  //曹%List<User> userList = userMapper.selectList(wrapper);userList.forEach(System.out::println);userMapper.selectList(wrapper);}/*** 测试or,默认and拼接条件*/@Testpublic void testOr() {LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();lambdaQueryWrapper.eq(User::getName, "曹丕");lambdaQueryWrapper.or();   //添加or条件lambdaQueryWrapper.eq(User::getAge, 22);/*** SELECT id,user_name,password,name,age,email,birthday FROM tb_user* WHERE name = ? OR age = ?*/List<User> userList = userMapper.selectList(lambdaQueryWrapper);userList.forEach(System.out::println);}//代码功能:在name为"张三", "李四", "王五"中 筛选password=123 或者age>20的人。@Testpublic void testLogicSelect() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.and(wp -> wp.eq("password", "123").or().ge("age", 20)).in("name", "张三", "李四", "王五");/*** SELECT id,user_name,password,name,age,email,birthday FROM tb_user* WHERE password = ? OR age >= ? AND name IN (?,?,?)* 在 MySQL 中,AND 的优先级高于 OR。这意味着当一个查询语句中同时包含 AND 和 OR 运算符                    时,AND 将首先执行,然后才是OR。*/List<User> userList = userMapper.selectList(wrapper);userList.forEach(user -> System.out.println(user));}}


http://www.ppmy.cn/embedded/31585.html

相关文章

React 第十八章 Hook useImperativeHandle

React 的 useImperativeHandle 是一个自定义 Hook。该 Hook 一般配合 React.forwardRef 使用&#xff0c;主要用于在父组件中可以使用 ref 获取子组件暴露出来的属性和方法。 useImperativeHandle 接受两个参数&#xff1a;ref 和创建子组件属性和方法的函数。 function Chil…

STM32入门_江协科技_3~4_OB记录的自学笔记_软件安装新建工程

3. 软件安装 3.1. 安装Keil5 MDK 作者的资料下载的连接如下&#xff1a;https://jiangxiekeji.com/download.html#32 3.2. 安装器件支持包 因为新的芯片层出不穷&#xff0c;所以需要安装Keil5提供的器件升级版对软件进行升级&#xff0c;从而支持新的芯片&#xff1b;如果不…

OpenWRT有线桥接部署教程

前言 之前咱们讲到OpenWRT部署WAN实现PPPoE拨号上网和自动获取IP模式上网的办法&#xff1a; OpenWRT设置PPPoE拨号教程 OpenWRT设置自动获取IP&#xff0c;作为二级路由器 这一次&#xff0c;咱们尝试用OpenWRT有线桥接上一级路由器的教程。 可能有小伙伴敏锐地发现了&am…

史上最复杂的探测器嫦娥六号,如何采取人类首份月背样品? | 最新快讯

作者&#xff1a;LM-51D-YZ4D2&#xff0c;航天爱好者 今天&#xff0c;长征五号遥八火箭即将从海南文昌航天发射场点火起飞&#xff0c;把嫦娥六号探测器送入预定轨道。作为嫦娥五号的备份器&#xff0c;嫦娥六号继承了嫦娥五号的结构&#xff0c;又针对月球背面着陆进行了优化…

深度学习之基于Tensorflow卷积神经网络智能体操健身系统

欢迎大家点赞、收藏、关注、评论啦 &#xff0c;由于篇幅有限&#xff0c;只展示了部分核心代码。 文章目录 一项目简介 二、功能三、系统四. 总结 一项目简介 一、项目背景 随着人们健康意识的提高和数字化技术的快速发展&#xff0c;智能健身系统逐渐成为健身领域的新趋势。…

苹果CMS V10萌芽采集插件Pro v10.7.3

苹果CMS V10萌芽采集插件Pro v10.7.3 使用说明: 将addons文件和static文件放到你苹果cms程序的根目录并覆盖&#xff0c; 在登录后台在应用-应用市场启用。http://你的域名/admin.php/admin/mycj/union.html 插件源码下载&#xff1a;https://download.csdn.net/download/m…

深入探究TCP/IP协议

一、引言 在信息技术飞速发展的今天&#xff0c;网络已成为人类社会不可或缺的部分。实现网络中计算机相互通信的关键之一便是TCP/IP协议。作为互联网的基础&#xff0c;TCP/IP协议确保了全球范围内的数据交换和信息共享。本文将深入探讨TCP/IP协议的概念、特点、组成、相关协…

逻辑漏洞:Cookie脆弱性导致的逻辑漏洞

前几天学习了逻辑漏洞中的越权漏洞和支付漏洞&#xff0c;今天学习一下cookie脆弱性导致的逻辑漏洞 还是和之前一样&#xff0c;所有内容都是参考别的大佬总结好的&#xff0c;我只是在这里进行学习练习 1、cookie介绍 用户在客户端 (一般为浏览器) 中访问某个页面 &#xff0…