【SpringBoot】使用Spring Boot、MyBatis-Plus和MySQL来实现增删改查操作,并添加自定义SQL查询。

使用Spring Boot、MyBatis-Plus和MySQL来实现增删改查操作,并添加自定义SQL查询。

1. 创建Spring Boot项目

你可以使用Spring Initializr来创建一个新的Spring Boot项目。在选择依赖项时,确保选择以下内容:

  • Spring Web
  • MyBatis-Plus Boot Starter
  • MySQL Driver
  • Lombok(用于简化Java代码)

2. 添加依赖

如果你使用的是Maven,确保在pom.xml中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3.4</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

3. 配置数据库连接

src/main/resources/application.properties中配置数据库连接信息。

spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis.mapper-locations=classpath:mapper/*.xml

4. 创建实体类

src/main/java/com/example/demo/entity目录下创建一个实体类,例如User

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("user")
public class User {
    @TableId
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

5. 创建Mapper接口

src/main/java/com/example/demo/mapper目录下创建一个Mapper接口,继承BaseMapper。这里同时给出使用注解和XML两种方式,二选一。

使用注解的方式

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT * FROM user WHERE age > #{age}")
    List<User> selectUsersOlderThan(@Param("age") int age);
}

使用XML文件的方式

首先,在src/main/resources/mapper目录下创建一个XML文件,例如UserMapper.xml

<?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">

<mapper namespace="com.example.demo.mapper.UserMapper">
    <select id="selectUsersOlderThan" resultType="com.example.demo.entity.User">
        SELECT * FROM user WHERE age > #{age}
    </select>
</mapper>

然后,在UserMapper接口中添加与XML文件中定义的方法一致的方法签名。

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    List<User> selectUsersOlderThan(@Param("age") int age);
}

6. 创建Service类

src/main/java/com/example/demo/service目录下创建一个Service接口。

package com.example.demo.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.entity.User;

import java.util.List;

public interface UserService extends IService<User> {
    List<User> getUsersOlderThan(int age);
}

src/main/java/com/example/demo/service/impl目录下创建Service实现类。

package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getUsersOlderThan(int age) {
        return userMapper.selectUsersOlderThan(age);
    }
}

7. 创建Controller类

src/main/java/com/example/demo/controller目录下创建一个Controller类,用于处理HTTP请求。

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    @PostMapping
    public boolean createUser(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping("/{id}")
    public boolean updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }

    @GetMapping("/older-than/{age}")
    public List<User> getUsersOlderThan(@PathVariable int age) {
        return userService.getUsersOlderThan(age);
    }
}

8. 创建数据库表

确保在MySQL数据库中创建对应的表。例如:

CREATE TABLE `user` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL,
  `age` INT NOT NULL,
  `email` VARCHAR(50),
  PRIMARY KEY (`id`)
);

9. 启动应用

确保所有配置和代码都正确,然后运行Spring Boot应用。你可以通过以下命令来启动应用:

mvn spring-boot:run

10. 测试API

你现在可以通过HTTP请求来访问和操作用户数据。以下是一些示例请求:

获取所有用户

curl -X GET http://localhost:8080/users

获取特定用户

curl -X GET http://localhost:8080/users/1

创建新用户

curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name":"John Doe","age":30,"email":"john.doe@example.com"}'

更新用户

curl -X PUT http://localhost:8080/users/1 -H "Content-Type: application/json" -d '{"name":"Jane Doe","age":25,"email":"jane.doe@example.com"}'

删除用户

curl -X DELETE http://localhost:8080/users/1

获取年龄大于特定值的用户

curl -X GET http://localhost:8080/users/older-than/30

通过这些步骤,你可以在Spring Boot项目中使用MyBatis-Plus和MySQL实现增删改查操作,并添加自定义SQL查询。这样,你不仅可以利用MyBatis-Plus的简洁性,还能灵活地支持复杂的SQL查询。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

将 hugo 博客搬迁到服务器

1. 说明 在 Ubuntu 22.04 上使用 root 账号&#xff0c;创建普通账号&#xff0c;并赋予 root 权限。 演示站点&#xff1a;https://woniu336.github.io/ 魔改hugo主题: https://github.com/woniu336/hugo-magic 2. 服务器配置 建立 git 用户 adduser git安装 git sudo apt …

C/C++ 多线程[1]---线程创建+线程释放+实例

文章目录 前言1. 多线程创建2. 多线程释放3. 实例总结 前言 说来惭愧&#xff0c;写了很久的代码&#xff0c;一个单线程通全部。可能是接触的项目少吧&#xff0c;很多多线程的概念其实都知道&#xff0c;但是实战并没有用上。前段时间给公司软件做一个进度条&#xff0c;涉及…

亲测解决Verifying shim SBAT data failed: Security Policy Violation

在小虎用u盘安装ubuntu系统的时候&#xff0c;笔记本出现了这个问题&#xff0c;解决方法是管关闭security boot。 解决方法 利用F2\F10\F12进入Bios设置&#xff0c;关闭security boot即可。 Use F2 to enter the bios security settings, close it. 参考 Verifying shim…

揭秘Semantic Kernel:用AI自动规划和执行用户请求

在我们日益高效的开发世界中&#xff0c;将任务自动化并智能规划变得越来越必要。今天&#xff0c;我要给大家介绍一个强大的概念——Semantic Kernel中的planner功能。通过这篇文章&#xff0c;我们会学习到planner的工作原理以及如何实现智能任务规划。 什么是planner&#x…

Spring GateWay自定义断言工厂

文章目录 概要整体架构流程最终的处理效果小结 概要 我们在线上系统部署了&#xff0c;灰度环境和生产环境时&#xff0c;可以通过自定义断言工厂去将请求需要路由到灰度环境的用户调用灰度的的服务集群&#xff0c;将正常的用户调用正常集群。 这样&#xff0c;我们可以在上线…

R语言论文插图模板第7期—分组散点图

在之前的文章中&#xff0c;分享过R语言折线图的绘制模板&#xff1a; 柱状图的绘制模板&#xff1a; 本期再来分享一下散点图&#xff08;分组&#xff09;的绘制方法。 先来看一下成品效果&#xff1a; 特别提示&#xff1a;本期内容『数据代码』已上传资源群中&#xff0c;…

碰撞检测 | 基于ROS Rviz插件的多边形碰撞检测仿真平台

目录 0 专栏介绍1 基于多边形的碰撞检测2 碰撞检测仿真平台搭建2.1 多边形实例2.2 外部服务接口2.3 Rviz插件化 3 案例演示3.1 功能介绍3.2 绘制多边形 0 专栏介绍 &#x1f525;课设、毕设、创新竞赛必备&#xff01;&#x1f525;本专栏涉及更高阶的运动规划算法轨迹优化实战…

【附源码】Python :PYQT界面点击按钮随机变色

系列文章目录 Python 界面学习&#xff1a;PYQT界面点击按钮随机变色 文章目录 系列文章目录一、项目需求二、源代码三、代码分析3.1 导入模块&#xff1a;3.2 定义App类&#xff1a;3.3 构造函数&#xff1a;3.4 初始化用户界面&#xff1a;3.5 设置窗口属性&#xff1a;3.6 …

基于距离度量学习的异常检测:一种通过相关距离度量的异常检测方法

异常通常被定义为数据集中与大多数其他项目非常不同的项目。或者说任何与所有其他记录(或几乎所有其他记录)显著不同的记录,并且与其他记录的差异程度超出正常范围,都可以合理地被认为是异常。 例如上图显示的数据集中,我们有四个簇(A、B、C和D)和三个位于这些簇之外的点:P1、P…

client网络模块的开发和client与server端的部分联动调试

客户端网络模块的开发 我们需要先了解socket通信的流程 socket通信 server端的流程 client端的流程 对于closesocket()函数来说 closesocket()是用来关闭套接字的,将套接字的描述符从内存清除,并不是删除了那个套接字,只是切断了联系,所以我们如果重复调用,不closesocket()…

Agentic Security:一款针对LLM模型的模糊测试与安全检测工具

关于Agentic Security Agentic Security是一款针对LLM模型的模糊测试与安全检测工具&#xff0c;该工具可以帮助广大研究人员针对任意LLM执行全面的安全分析与测试。 请注意 Agentic Security 是作为安全扫描工具设计的&#xff0c;而不是万无一失的解决方案。它无法保证完全防…

C++(11)类语法分析(2)

C(10)之类语法分析(2) Author: Once Day Date: 2024年8月17日 一位热衷于Linux学习和开发的菜鸟&#xff0c;试图谱写一场冒险之旅&#xff0c;也许终点只是一场白日梦… 漫漫长路&#xff0c;有人对你微笑过嘛… 全系列文章可参考专栏: 源码分析_Once-Day的博客-CSDN博客 …

Python数据结构:集合详解(创建、集合操作)④

文章目录 1. Python集合概述2. 创建集合2.1 使用花括号 {} 创建集合2.2 使用 set() 函数创建集合2.3 创建空集合 3. 集合操作3.1 添加和删除元素3.2 集合的基本操作3.3 集合的比较操作3.4 不可变集合&#xff08;frozenset&#xff09; 4. 综合例子&#xff1a;图书管理系统 Py…

30秒内批量删除git本地分支

在开发过程中&#xff0c;我们经常需要对本地的 Git 分支进行管理。有时&#xff0c;由于各种原因&#xff0c;我们可能需要批量删除本地的分支。这可能是因为某些分支已经不再需要&#xff0c;或者是为了清理本地的分支列表&#xff0c;以保持整洁和易于管理。 要批量删除本地…

没有用的小技巧之---接入网线,有内网没有外网,但是可以登录微信

打开控制面板&#xff0c;找到网络和Internet 选择Internet选项 点击连接&#xff0c;选择局域网设置 取消勾选代理服务器

开放式耳机会打扰到别人吗?四款漏音处理做的好的蓝牙耳机

一般情况下&#xff0c;开放式耳机不会打扰到别人。 开放式耳机通常采用全开放设计&#xff0c;声音不会完全封闭在耳朵里&#xff0c;而是向四周扩散&#xff0c;相比封闭式耳机&#xff0c;其对外界环境的噪音影响更小 。而且现在的开放式耳机在技术上已经有了很大的进步&am…

[数据集][目标检测]工程机械车辆检测数据集VOC+YOLO格式3189张10类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;3189 标注数量(xml文件个数)&#xff1a;3189 标注数量(txt文件个数)&#xff1a;3189 标注…

springboot的自动配置和怎么做自动配置

目录 一、Condition 1、Condition的具体实现 2、Condition小结 &#xff08;1&#xff09;自定义条件 &#xff08;2&#xff09;SpringBoot 提供的常用条件注解 二、Enable注解 三、EnableAutoConfiguration 注解和自动配置 1、EnableAutoConfiguration的三个注解属性…

git 学习--GitHub Gitee码云 GitLab

1 集中式和分布式的区别 1.1 集中式 集中式VCS必须有一台电脑作为服务器&#xff0c;每台电脑都把代码提交到服务器上&#xff0c;再从服务器下载代码。如果网络出现问题或服务器宕机&#xff0c;系统就不能使用了。 1.2 分布式 分布式VCS没有中央服务器&#xff0c;每台电脑…

Python编码系列—Python SQL与NoSQL数据库交互:深入探索与实战应用

&#x1f31f;&#x1f31f; 欢迎来到我的技术小筑&#xff0c;一个专为技术探索者打造的交流空间。在这里&#xff0c;我们不仅分享代码的智慧&#xff0c;还探讨技术的深度与广度。无论您是资深开发者还是技术新手&#xff0c;这里都有一片属于您的天空。让我们在知识的海洋中…