当前位置: 首页 > article >正文

SpringBoot+MyBatis

切换数据库连接词

引入数据库连接词的依赖,配置数据库连接池的类型;

编写测试类:

package org.example.threelayerdecouplingdomeapplication2;import org.example.threelayerdecouplingdomeapplication2.mapper.UserMapper;
import org.example.threelayerdecouplingdomeapplication2.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTest//而用程序在运行时,会自动的为该接口创建一个实现类对象(代理对象),并且会自动将该实现类对象存入IOC容器- bean no usages
class ThreeLayerDecouplingDomeApplication2ApplicationTests {@Autowiredprivate UserMapper userMapper;@Testpublic void testFindAll(){List<User> users = userMapper.findAll();System.out.println(users);}}

使用Mapper来操纵数据库

在 MyBatis 框架里,@Mapper 注释的作用是把接口标记成 MyBatis 的映射器接口。这意味着 MyBatis 会自动为这个接口创建代理实现类,进而让开发者能够直接通过调用接口方法来执行 SQL 操作,无需手动编写实现代码。

package org.example.threelayerdecouplingdomeapplication2.mapper;import org.apache.ibatis.annotations.*;
import org.example.threelayerdecouplingdomeapplication2.pojo.User;import java.util.List;@Mapper
public interface UserMapper {@Select("SELECT * FROM people")List<User> findAll();@Select("SELECT * FROM people WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO people(name, age, status, gender, tp) VALUES(#{name}, #{age},#{status},#{gender},#{tp})")@Options(useGeneratedKeys = true, keyProperty = "id")int insert(User user);@Update("UPDATE people SET name=#{name}, age=#{age} WHERE ID=#{id}")int update(User user);@Delete("DELETE FROM people WHERE ID = #{id}")int delete(Integer id);
}

删除用户信息需要使用到占位符#{};

查询用户

当传入的形参有多个时候,因为在编译后形成的字节码文件只有类型,所以要用@Param注解给每一个形参起别名,让它能后准确对应sql语句的占位符。

两种占位符的区别

用注入来直接使用接口中的sql

package org.example.threelayerdecouplingdomeapplication2.service.impl;import org.example.threelayerdecouplingdomeapplication2.mapper.UserMapper;
import org.example.threelayerdecouplingdomeapplication2.pojo.User;
import org.example.threelayerdecouplingdomeapplication2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl implements UserService {@Autowired// 自动注入private UserMapper userMapper;public List<User> findAll() {return userMapper.findAll();}public User findById(Long id) {return userMapper.findById(id);}public int insert(User user) {return userMapper.insert(user);}public int update(User user) {return userMapper.update(user);}public int delete(Integer id) {return userMapper.delete(id);}
}

同样的使用注入来的控制器

package org.example.threelayerdecouplingdomeapplication2.controller;import org.example.threelayerdecouplingdomeapplication2.pojo.User;
import org.example.threelayerdecouplingdomeapplication2.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserServiceImpl userService;@GetMapping("/findAll")public List<User> findAll() {return userService.findAll();}@GetMapping("/{id}")public User findById(@PathVariable Long id) {return userService.findById(id);}@PostMappingpublic int insert(@RequestBody User user) {return userService.insert(user);}@PutMappingpublic int update(@RequestBody User user) {return userService.update(user);}@DeleteMapping("/{id}")public int delete(@PathVariable Integer id) {return userService.delete(id);}
}

1. @RestController

  • 作用:将该类标记为 RESTful 控制器,相当于@Controller + @ResponseBody的组合。
  • 效果
    • 类中的方法返回值会自动序列化为 JSON/XML 等格式(取决于客户端的Accept头)。
    • 无需在每个方法上单独添加@ResponseBody

2. @RequestMapping("/users")

  • 作用:为整个控制器指定基础 URL 路径。
  • 效果:所有该类中的请求处理方法的 URL 都会以/users开头(例如/users/findAll)。

3. @Autowired

  • 作用:自动注入依赖的 Bean(这里是UserServiceImpl)。
  • 效果
    • Spring 会在容器中查找UserServiceImpl类型的 Bean,并将其注入到userService字段。
    • 无需手动创建UserServiceImpl的实例(依赖反转)。

4. HTTP 请求方法注解

@GetMapping
  • 作用:处理 HTTP GET 请求。
  • 示例
    • @GetMapping("/findAll"):处理GET /users/findAll请求。
    • @GetMapping("/{id}"):处理GET /users/{id}请求(例如/users/1),其中{id}是路径变量。
@PostMapping
  • 作用:处理 HTTP POST 请求(通常用于创建资源)。
  • 示例@PostMapping:处理POST /users请求。
@PutMapping
  • 作用:处理 HTTP PUT 请求(通常用于更新资源)。
  • 示例@PutMapping:处理PUT /users请求。
@DeleteMapping
  • 作用:处理 HTTP DELETE 请求(通常用于删除资源)。
  • 示例@DeleteMapping("/{id}"):处理DELETE /users/{id}请求。

5. 参数绑定注解

@PathVariable
  • 作用:从 URL 路径中提取变量值。
  • 示例
    • @PathVariable Long id:从 URL 中提取id参数(例如/users/1中的1),并转换为Long类型。
@RequestBody
  • 作用:将 HTTP 请求的 JSON/XML 体反序列化为 Java 对象。
  • 示例
    • @RequestBody User user:将请求体中的 JSON 数据映射到User对象(需确保 JSON 字段与User类属性名匹配)。

SpringBoot中的配置文件

 SpringBoot项目提供了多种属性配置方式(properties、yaml、yml)。

properties

例如:

yaml、yml

格式

·数值前边必须有空格,作为分隔符
·使用缩进表示层级关系,缩进时,不允许使用Tab键,只能用空格( idea中会自动将Tab转换为空格)
·缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
·#表示注释,从这个字符一直到行尾,都会被解析器忽略

定义对象/Map集合

:后面要有空格

定义数组/List/Set集合

每一个元素前面都有一个空格

注意:在yml配置文件中,如果配置项的值是以开头的,值要使用"引起来,因为以0开头的在yml中表示8进制数据

http://www.lryc.cn/news/2386431.html

相关文章:

  • wireshark: Display Filter Reference
  • Java基础 Day19
  • VMware+Windows 11 跳过安装阶段微软账号登录
  • HarmonyOS开发-应用间跳转
  • 网工每日一练
  • 使用 Navicat 17 for PostgreSQL 时,请问哪个版本支持 PostgreSQL 的 20150623 版本?还是每个版本都支持?
  • 校园二手交易系统
  • 基于pycharm,python,flask,sklearn,orm,mysql,在线深度学习sql语句检测系统
  • LangChain02-Agent与Memory模块
  • upload-labs通关笔记-第17关文件上传之二次渲染gif格式
  • 计算机网络学习20250525
  • STM32中的SPI通信协议
  • 从版本控制到协同开发:深度解析 Git、SVN 及现代工具链
  • redis Pub/Sub 简介 -16 (PUBLISH、SUBSCRIBE、PSUBSCRIBE)
  • 《黄帝内经》数学建模与形式化表征方式的重构
  • PyTorch Image Models (timm) 技术指南
  • 基于Scikit-learn与Flask的医疗AI糖尿病预测系统开发实战
  • 掌握聚合函数:COUNT,MAX,MIN,SUM,AVG,GROUP BY和HAVING子句的用法,Where和HAVING的区别
  • 【Node.js】高级主题
  • 【Linux】定时任务 Crontab 与时间同步服务器
  • 【TCP/IP协议族详解】
  • 蓝桥杯电子赛_零基础利用按键实现不同数字的显现
  • Docker架构详解
  • Rust 学习笔记:关于生命周期的练习题
  • Spring AI 模块架构与功能解析
  • 单元测试学习笔记
  • 多模态大语言模型arxiv论文略读(九十)
  • (1-6-1)Java 集合
  • spring5-配外部文件-spEL-工厂bean-FactoryBean-注解配bean
  • [安全清单] Linux 服务器安全基线:一份可以照着做的加固 Checklist