SpringBoot+Maven笔记

news2024/10/6 22:24:35

文章目录

  • 1、启动类
  • 2、mapper 接口
  • 3、控制类
  • 4、补充:返回数据时的封装
  • 5、补充
    • a、mybatisplus

1、启动类

在启动类上加入@MapperScan扫描自己所写的mapper接口

package com.example.bilili_springboot_study;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.bilili_springboot_study.mapper")
public class BililiSpringBootStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(BililiSpringBootStudyApplication.class, args);
    }

}

2、mapper 接口


注意加上@Mapper注解

package com.example.bilili_springboot_study.mapper;

import com.example.bilili_springboot_study.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user")
    public List<User> selectAll();
}

如果接口中的sql语句比较麻烦,也可在resources目录下,新建mapper/UserMapper.xml文件,通过该文件控制sql语句例如:

<mapper namespace="com.whd.system.mapper.SysUserMapper"> 对应所绑定的接口的位置

<?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.whd.system.mapper.SysUserMapper">
    <select id="getUserById" resultType="com.example.bilili_springboot_study.entity.User">
        select *
        from user
        where id = #{id}

    </select>	

</mapper>

  在该文件中,select语句要加上返回值的类型,使用resultType=" " 进行设置,他指定了返回的结果类型为什么,id为接口中的方法名

   insert update 一般都是int ,因为返回的是影响的结果数

   在接口的方法中,如果要进行传参,在sql中使用 #{ } 来进行引用,注意变量和形参一样


完整事例:
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.bilili_springboot_study.mapper.UserMapper">
<select id="getUserById" resultType="com.example.bilili_springboot_study.entity.User">
    select * from user where id = #{id}

</select>

</mapper>

mapper 接口
UserMapper.java

package com.example.bilili_springboot_study.mapper;

import com.example.bilili_springboot_study.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user")
    public List<User> selectAll();

    User getUserById(int id);
}

控制器
UserController.java

package com.example.bilili_springboot_study.controller;

import com.example.bilili_springboot_study.entity.User;
import com.example.bilili_springboot_study.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/select/userAll")
    public List<User> getAllUser() {
        return userMapper.selectAll();
    }

    @GetMapping("/find/user/{id}")
    public User findUserById(@PathVariable int id) {
        return userMapper.getUserById(id);
    }

}


3、控制类

注意要引入所写的接口

 @Autowired
    private UserMapper userMapper;

  在使用接口查询数据库中的信息后,直接return即可返回json格式的数据,也可以将查询到的数据在此进行处理然后再return给前端

package com.example.bilili_springboot_study.controller;

import com.example.bilili_springboot_study.entity.User;
import com.example.bilili_springboot_study.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/select/userAll")
    public List<User> getAllUser() {
        return userMapper.selectAll();
    }

<--   ---------   以上方法通过接口实现  -->

    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable int id) {
        System.out.println(id);
        return " 根据用户id获取用户信息";
    }

    @PostMapping("/user")
    public String saveUser() {
        return "添加用户信息";
    }

    @PutMapping("/user")
    public String updateUser() {
        return "更新用户信息";
    }

    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable int id) {
        System.out.println(id);
        return "根据用户id删除用户";
    }

}

4、补充:返回数据时的封装

  创建有着泛型的类,和一个枚举类型(设置状态码),以后在返回数据的时候,不仅仅是直接返回接口返回的数据,而是通过AxiosResult<T>实现,

package com.whd.system.common;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AxiosResult<T> {
    private int code;
    private String msg;
    private T data;

    private AxiosResult(CodeEnum codeEnum, T data) {
        this.code = codeEnum.getCode();
        this.msg = codeEnum.getMsg();
        this.data = data;
    }

    private AxiosResult(CodeEnum codeEnum) {
        this.code = codeEnum.getCode();
        this.msg = codeEnum.getMsg();
    }

    //方法重载
    //成功
    public static <T> AxiosResult<T> success(T data){
        return new AxiosResult<T>(CodeEnum.SUCCESS,data);
    }

    public static <T> AxiosResult<T> success(CodeEnum codeEnum,T data){
        return new AxiosResult<T>(codeEnum,data);
    }
    //失败
    public static <T> AxiosResult<T> error(){
        return new AxiosResult<T>(CodeEnum.ERROR);
    }

    public static <T> AxiosResult<T> error(CodeEnum codeEnum){
        return new AxiosResult<T>(codeEnum);
    }
}

package com.whd.system.common;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum CodeEnum {
    SUCCESS(200, "success"),
    ERROR(500, "error"),
    UNKNOWN_ERROR(100, "未知错误"),
    USER_LOGIN_ERROR(501, "用户名或者密码有误"),
    USER_INVALID_ERROR(502, "用户已被禁用");

    private final int code;
    private final String msg;
}



例如以下例子:

package com.whd.system.controller;

import com.whd.system.common.AxiosResult;
import com.whd.system.common.CodeEnum;
import com.whd.system.domain.SysUser;
import com.whd.system.domain.vo.SysRoleVo;
import com.whd.system.domain.vo.SysUserVo;
import com.whd.system.mapper.SysUserMapper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
//@CrossOrigin // 允许类跨域请求
public class SysUserController {

    private static final String PAO_PATH = "http://127.0.0.1:8080";
    @Autowired
    private SysUserMapper SysUserMapper;

    @PostMapping("/login")
    public AxiosResult<Integer> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        SysUser user = SysUserMapper.selectByUser(username, password);
        if (user == null) {
            return AxiosResult.error(CodeEnum.USER_LOGIN_ERROR);
        }
        return AxiosResult.success(user.getId());
    }
//查找用户信息
    @GetMapping("/find/{id}")
    public AxiosResult<Map<String, Object>> findUserAndRoleInfo(@PathVariable("id") Integer id) {
        Map<String, Object> map = SysUserMapper.findUserAndeRole(id);
        return AxiosResult.success(map);
    }

    // 查找角色信息
    @GetMapping("/find/getRoleList")
    public AxiosResult<List<SysRoleVo>> findRoleInfo() {
        List<SysRoleVo> list = SysUserMapper.findRoleInfo();
        return AxiosResult.success(list);
    }

// 修改管理/用户信息 状态 0/1
    @GetMapping("/update/status/{id}/{status}")
    public AxiosResult<Integer> updateStatus(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
        int i = SysUserMapper.updateStatus(id, status);
        return AxiosResult.success(i);
    }

// 修改管理员信息
    @PostMapping("/update/adminInfo")
    public AxiosResult<Integer> updateAdminInfo(@RequestBody Map<String, Object> params) {

        String id = (String) params.get("id");
        String username = (String) params.get("username");
        String phone = (String) params.get("phone");
        String sex = (String) params.get("sex");
        String password = (String) params.get("pass");
        int roleId = (int) params.get("role");

        Map<String, Object> map=new HashMap<>();
        map.put("id", id);
        map.put("username", username);
        map.put("phone", phone);
        map.put("sex", sex);
        map.put("password", password);
        map.put("roleId", roleId);

        int i = SysUserMapper.updateAdminInfo(map);

        return AxiosResult.success(1);
    }

}

注意本例子中的这个方法:他传进.xml中的是一个map类型的数据,那么在使用的时候,还要指定他的类型

// 修改管理员信息
    @PostMapping("/update/adminInfo")
    public AxiosResult<Integer> updateAdminInfo(@RequestBody Map<String, Object> params) {

        String id = (String) params.get("id");
        String username = (String) params.get("username");
        String phone = (String) params.get("phone");
        String sex = (String) params.get("sex");
        String password = (String) params.get("pass");
        int roleId = (int) params.get("role");

        Map<String, Object> map=new HashMap<>();
        map.put("id", id);
        map.put("username", username);
        map.put("phone", phone);
        map.put("sex", sex);
        map.put("password", password);
        map.put("roleId", roleId);

        int i = SysUserMapper.updateAdminInfo(map);

        return AxiosResult.success(1);
    }

    <update id="updateAdminInfo" parameterType="map">
        UPDATE sys_user
        SET
            username = #{username, jdbcType=VARCHAR},
            phone = #{phone, jdbcType=VARCHAR},
            gender = #{sex, jdbcType=VARCHAR},
            password = #{password, jdbcType=VARCHAR},
            role_uid = #{roleId, jdbcType=INTEGER}
        WHERE id = #{id, jdbcType=VARCHAR}
    </update>

5、补充

a、mybatisplus

  在mapper 接口中,通过继承BaseMapper<T>类,可以实现所有的增删改查,复杂的可能还是要手敲的
  1、由于我们写的实体类的名字可能和表的名字有很大差异,所以在继承后,所用的实体类添加@TableName("表名")注解,用户确定该实体类所对应的表的名字
  2、实体类的名字不一定要和表中字段的名字一致,但是,不一致的要添加@Result(column = "db_column_name", property = "propertyName")用于映射,不然怎么实现智能化对应了,但是还是建议直接用一样的就行了
  对于 mybatisplus 还有很多用法,自行查找吧 >_<

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

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

相关文章

OpenGL3.3_C++_Windows(10)

最终演示 ​ demo演示 Assimp模型渲染 模型导入库Assimp&#xff1a;导入很多种不同的模型文件格式&#xff0c;加载至Assimp的通用数据结构&#xff08;树形&#xff09;中&#xff0c;不论导入的是什么种类的文件格式&#xff0c;用同一种方式访问我们需要的数据。 Assimp库…

计算机网络(8) Finite State Machines(有限状态机)

一.建立连接&#xff08;三次握手&#xff09; 建立连接过程中的状态转换如下&#xff1a; 客户端&#xff1a; 发送SYN CLOSED >>>>>>>>>>>>>>SYN SENT(第一次握手) 接收SYNACK发送ACK …

2779. 数组的最大美丽值

简单翻译一下题目意思&#xff1a; 对于每个 nums[i] 都可以被替换成 [nums[i]-k, nums[i]k] 区间中的任何数&#xff0c;区间左右是闭的。在每个数字可以替换的前提下&#xff0c;返回数组中最多的重复数字的数量。 第一想法是用一个哈希表&#xff0c;Key 是可以被替换的数…

统计信号处理基础 习题解答10-12

题目&#xff1a; 如果&#xff0c;其中&#xff1a; 对某个&#xff0c;令。证明当时使最大。另外&#xff0c;证明。它们为什么是相同的&#xff1f;如果&#xff0c;基于的的MMSE估计量是什么&#xff1f; 解答&#xff1a; 根据多维高斯分布的定义&#xff0c;可以得到&am…

探索未来边界:前沿技术引领新纪元

目录 引言 一、人工智能与深度学习&#xff1a;智慧生活的引擎 1.医疗应用 2.智能家居 3.自动驾驶 二、量子计算&#xff1a;解锁宇宙的密钥 1.量子比特示意图 2.量子计算机实物图 3.分子模拟应用 三、生物技术&#xff1a;生命科学的革新 1.CRISPR-Cas9基因编辑图 2.合成生…

希亦、添可、石头洗地机哪款好用?2024洗地机深度测评

今年的洗地机市场竞争异常激烈&#xff0c;各大品牌纷纷推出了自己的旗舰产品。这对消费者来说是个好消息&#xff0c;因为有更多的选择空间。然而&#xff0c;面对如此多的优质洗地机&#xff0c;选择合适的一款也成了一种“幸福的烦恼”。 作为一个专业的测评人士&#xff0…

Java中ArrayList(顺序表)的自我实现(如果想知道Java中怎么自我实现ArrayList,那么只看这一篇就足够了!)

前言&#xff1a;在 Java 编程中&#xff0c;ArrayList 是一种非常常用的数据结构&#xff0c;它提供了动态数组的实现方式&#xff0c;可以方便地存储和操作数据。相比于传统的数组&#xff0c;ArrayList 具有更多的灵活性和便利性&#xff0c;可以根据需要动态地调整大小&…

深入理解计算机系统 CSAPP 家庭作业6.37

S256 N64时: sumA:这个很简单了,不说了 sumB:如下表. i递增时一直不命中 读到j1,i0 即读a[0][1]时 组0存放的是a[48][0] -a[48][3] 接着读a[1][1]时,组16放的是a[49][0]-a[49][3],j递增之后还是一直不命中 组0:a[0][0]a[16][0]a[32][0]a[48][0]a[0][1]组16:a[1][0]a[17][…

Python设计模式 - 简单工厂模式

定义 简单工厂模式是一种创建型设计模式&#xff0c;它通过一个工厂类来创建对象&#xff0c;而不是通过客户端直接实例化对象。 结构 工厂类&#xff08;Factory&#xff09;&#xff1a;负责创建对象的实例。工厂类通常包含一个方法&#xff0c;根据输入参数的不同创建并返…

训练营第三十八天 | 309.最佳买卖股票时机含冷冻期动态规划系列七总结714.买卖股票的最佳时机含手续费股票问题总结篇!

309.最佳买卖股票时机含冷冻期 力扣题目链接(opens new window) 给定一个整数数组&#xff0c;其中第 i 个元素代表了第 i 天的股票价格 。 设计一个算法计算出最大利润。在满足以下约束条件下&#xff0c;你可以尽可能地完成更多的交易&#xff08;多次买卖一支股票&#x…

泛微开发修炼之旅--15后端开发连接外部数据源,实现在ecology系统中查询其他异构系统数据库得示例和源码

文章链接&#xff1a;15后端开发连接外部数据源&#xff0c;实现在ecology系统中查询其他异构系统数据库得示例和源码

IT入门知识博客文章大纲(0/10)

IT入门知识博客文章大纲 引言 什么是IT&#xff1f; 信息技术&#xff08;Information Technology&#xff09;&#xff0c;互联网技术是指在计算机技术的基础上开发建立的一种信息技术 。互联网技术通过计算机网络的广域网使不同的设备相互连接&#xff0c;加快信息的传输速度…

STM32项目分享:车牌号识别系统

目录 一、前言 二、项目简介 1.功能详解 2.主要器件 三、原理图设计 四、PCB硬件设计 1.PCB图 2.PCB板打样焊接图 五、程序设计 六、实验效果 七、资料内容 项目分享 一、前言 项目成品图片&#xff1a; 哔哩哔哩视频链接&#xff1a; https://www.bilibili.…

MapReduce Simplified Data Processing on Large Clusters 论文笔记

2003年USENIX&#xff0c;出自谷歌&#xff0c;开启分布式大数据时代的三篇论文之一&#xff0c;作者是 Jeffrey 和 Sanjay&#xff0c;两位谷歌巨头。 Abstract MapReduce 是一种变成模型&#xff0c;用于处理和生成大规模数据。用户指定 map 函数处理每一个 key/value 对来…

手机上安装AI模型是一种什么体验?

昨天参加微软的AI DAY活动&#xff0c;看到微软的技术大佬分享了一个场景&#xff0c;就是坐飞机从上海到北京&#xff0c;机长广播因为天气原因&#xff0c;飞机需要盲降&#xff0c;他说当时听到盲降第一反应感觉有点恐慌&#xff0c;但是因为飞机上受限于网络环境&#xff0…

TIA博途中库类型和库元素的基本使用方法介绍

TIA博途中库类型和库元素的基本使用方法介绍 TIA博途中有两种不同类型的库: “项目库” “全局库” 内容由两种存储类型组成: • “类型” • “模板副本” (1) “项目库” – 集成在项目中,与项目一起管理 – 允许项目内可重复使用 (2) “全局库” – 独立库 – 可在…

MyBatis的逆向工程详细步骤操作

1. MyBatis的逆向工程详细步骤操作 文章目录 1. MyBatis的逆向工程详细步骤操作2. 逆向工程配置与生成2.1 MyBatis3Simple&#xff1a;基础版&#xff0c;只有基本的增删改查2.1.1 第一步&#xff1a;在pom.xml 中添加逆向工程插件2.1.2 第二步&#xff1a;配置 generatorConfi…

网络安全攻防基础入门笔记--操作系统名词解释文件下载反弹shell防火墙绕过

渗透测试常用专业术语 POC,EXP,Payload,Shellcode POC 全程Proof of Concept,中文"概念验证",常指一段漏洞证明的代码 EXP 全程Exploit ,中文"利用",指利用系统漏洞进行攻击的动作 Payload 中文"有效载荷",指成功Exploit之后,真正在目标系…

屹晶微EG3002 单通道功率MOSFET驱动芯片 贴片SOP8

EG3002作为一款功率MOSFET驱动芯片&#xff0c;它的应用领域主要取决于其技术参数和性能特点。根据之前提供的信息&#xff0c;EG3002可能适用于以下领域&#xff1a; 1. 电源管理&#xff1a;用于高效率电源转换器&#xff0c;如开关电源&#xff08;SMPS&#xff09;、电池充…

(虚拟机)VMware软件的安装及Ubuntu系统安装

一、VMware软件的安装 软件下载&#xff0c;可以自己找或者百度网盘下载&#xff1a; 通过百度网盘分享的文件&#xff1a;ubuntu16…等2个文件 链接:https://pan.baidu.com/s/1VEnZKY9DJ1T1vC3ae20gKQ 提取码:11b6 复制这段内容打开「百度网盘APP 即可获取」 1、解压VMwar…