Z¢&H 2025-03-04 20:25 采纳率: 70%
浏览 50

springboot 使用postman传测试数据,但是没有插入数据,显示数据为null

这是我Controller层的代码

package cn.edu.sdpt.mybatis_select.controller;
import cn.edu.sdpt.mybatis_select.entity.User;
import cn.edu.sdpt.mybatis_select.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 {
    @Autowired
    //Controller层要调用service层的方法 注入一个userservice对象
    UserService userService;
//    private List<User> user;

    @RequestMapping(value = "/query", method = RequestMethod.GET)

    public User query(@RequestParam("id") Long id) {
    //User user = userService.queryById(id);
        User user = userService.queryByIdNew(id);
        return user;
    }


    // todo post方法,实现增、删、改 传参都是User
    //增加一个用户
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Boolean addUser(@RequestBody User user) {
    //System.out.println("aaa");
        Boolean add = userService.addUser(user);
        return add;

    }

    //删除一个用户
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Boolean deleteUser(@RequestBody User user) {
    //测试
    //System.out.println("ajsshsd");
    //return Boolean.TRUE;
        Boolean del = userService.deleteUser(user);
        return del;
    }

    //更新一个用户数据
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Boolean updateUser(@RequestBody User user) {
    //测试
    //return Boolean.TRUE;
        Boolean up = userService.updateUser(user);
        return up;
    }

//    //查询所有用户信息以列表形式返回
//    @RequestMapping(value = "/select",method = RequestMethod.POST)
//    public List<User> selectUser(@RequestBody List<User> user) {
//        this.user = user;
//        List<User> sel = userService.selectAllUser();
//        return sel;
//
//    }
    

//    //查询数据 指定id-----还没写完
//    @RequestMapping(value = "/selectbyid",method = RequestMethod.POST)
//    public User selectUserById(@RequestBody Long id) {
//        User u = userService.selectUserById(id);
//        return u;
//    }

}

这是我的实体类

package cn.edu.sdpt.mybatis_select.entity;


import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Data
@TableName(value = "user")
//lombok 在编译阶段,为实体类自动生成setter、getter方法 eg:toString
//引入lombok需要在pom文件中引入依赖 还需要在实体类上添加注解
//添加完毕记得刷新一下maven
//@Data是lombok提供的注解

public class User {
    private static final long serialVersionUID = 1L;
    @TableId
    @TableField

    private Long id;
    private String name;
    private Integer age;
    private String address;
    private String sex;
    private String phone;
    private String createTime;
    private String role;
    private String password;
    private String email;


}



这是我的UserMapper

package cn.edu.sdpt.mybatis_select.mapper;

import cn.edu.sdpt.mybatis_select.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;


@Mapper
public interface UserMapper {
//    @Select("select * from user")
//    List<User> queryAll();

    /**
     * 带参数查询
     * 使用@Param注解来指定参数名,然后在@Select注解中引用参数名
     * @param
     * @return
     */
    @Select("SELECT * FROM user WHERE id = #{userId}")
    User getUserById(@Param("userId") Long userId);
//    一般情况下@Param引号中的名称与int定义的保持一致

    /**
     * 增加一条数据(通过post方法)
     */
    @Insert("insert into user(name,age,address,phone,create_time,sex,role,password,email) " +
            "values (#{name},#{age},#{address},#{phone},#{createTime},#{sex},#{role},#{password},#{email})")
    Integer insert(User user);

    /**
     * 删除一条数据(通过post方法)
     *
     */
    @Delete("delete from user where name = #{name}")
    Integer delete(User user);


    /**
     * 更新一条数据
     */
    @Update("update user set address=#{address},phone=#{phone} where id = 3")
    Integer update(User user);



    /**
     * 查询所有语句
     */
    @Select("select * from user")
    List<User> selectAll();
}


这是我的Service层


package cn.edu.sdpt.mybatis_select.service;

import cn.edu.sdpt.mybatis_select.entity.User;
import cn.edu.sdpt.mybatis_select.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
//调用Mapper层对应的方法执行SQL查询 所以要注入Mapper

//    public User queryById(Long id) {
//        List<User> res =  userMapper.queryAll();
//        for (User user : res) {
//            if (user.getId().equals(id)) {
//                return user;
//            }
//        }
//        return null;
//    }

    public User queryByIdNew(Long id) {
        User res = userMapper.getUserById(id);
        return res;
    }


    public Boolean addUser(User user) {
        Integer result = userMapper.insert(user);
        if(result.equals(1)) {
            return true;
        }
        else{
            return false;
        }
    }
    public Boolean deleteUser(User user) {
        Integer result = userMapper.delete(user);
        if (result.equals(1)) {
            return true;
        }
        else{
            return false;
        }

    }
    public Boolean updateUser(User user) {
        Integer result = userMapper.update(user);
        if (result.equals(1)) {
            return true;
        }
        else{
            return false;
        }

    }
    public List<User> selectAllUser() {
        List<User> userList = userMapper.selectAll();
        if(userList.isEmpty()){
            System.out.println("no user");
        }
        return userList;
    }

//    public User selectUserById(Long id) {
//
//    }
}



//那些可以更新 id不能 age name address更新


这是我的数据库

img

这是postman的测试结果

img


数据没有插进去为什么

img

  • 写回答

5条回答 默认 最新

  • 精通代码大仙 2025-03-06 10:31
    关注

    感谢您提出了这个好问题!对一个问题良好的界定,已经将问题解决一半了!让【精通代码大仙】来帮您解答,本回答来自人工整理,并深度整合参考了付费大模型GPT4、Claude 3.5 Sonnet,以及最新的推理模型DeepSeek R1(DeepSeek-V3:AI 省钱与高效的奇迹,打破技术壁垒的东方魔法Deepseek为什么会这么爆火?DeepSeek大模型技术解析:从架构到应用的全面探索)的参考答案,如果还有疑问可以点击头像关注私信或评论(如果小黑屋了,无法评论,请私信)。 如果答案让您满意,请采纳、关注,您的采纳与关注是我最大的动力!非常感谢!

    
    
    ```bash
    
    根据你提供的代码和描述,有几个可能的原因导致数据没有插入到数据库中。以下是一些常见的问题和解决方法:
    
    ### 1. 检查实体类字段与数据库字段是否匹配
    确保 `User` 实体类中的字段名称与数据库表中的字段名称完全一致(包括大小写)。例如,如果数据库中的字段是 `create_time`,那么实体类中的字段也应该是 `createTime`。
    
    ```java
    private String createTime; // 确保这个字段名与数据库字段名一致
    

    2. 检查 SQL 插入语句

    UserMapper 中的 insert 方法中,检查 SQL 语句是否正确,并且所有字段都已正确映射。

    @Insert("INSERT INTO user (name, age, address, phone, create_time, sex, role, password, email) " +
            "VALUES (#{name}, #{age}, #{address}, #{phone}, #{createTime}, #{sex}, #{role}, #{password}, #{email})")
    Integer insert(User user);
    

    确保 createTime 字段在数据库中是允许 NULL 值或者有默认值,否则需要提供一个非空值。

    3. 检查 Postman 请求体格式

    确保你在 Postman 中发送的 JSON 数据格式正确,并且字段名称与实体类中的字段名称一致。

    {
        "name": "张三",
        "age": 24,
        "address": "上海市",
        "phone": "1875623954",
        "createTime": "2023-06-19T06:39:58",
        "sex": "male",
        "role": "user",
        "password": "123456",
        "email": "123456@qq.com"
    }
    

    4. 检查日志输出

    addUser 方法中添加一些日志输出,以确认接收到的数据是否正确。

    public Boolean addUser(User user) {
        System.out.println("Received User: " + user); // 输出接收到的用户对象
        Integer result = userMapper.insert(user);
        if (result.equals(1)) {
            return true;
        } else {
            return false;
        }
    }
    

    5. 检查数据库连接和事务配置

    确保你的 Spring Boot 应用程序正确配置了数据库连接,并且事务管理器配置正确。可以在 application.propertiesapplication.yml 文件中检查数据库配置。

    spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=root
    spring.jpa.hibernate.ddl-auto=update
    

    6. 检查 MyBatis Plus 配置

    如果你使用的是 MyBatis Plus,确保在 application.propertiesapplication.yml 文件中正确配置了 MyBatis Plus。

    mybatis-plus.mapper-locations=classpath:mapper/*.xml
    mybatis-plus.type-aliases-package=cn.edu.sdpt.mybatis_select.entity
    

    7. 检查数据库权限

    确保数据库用户具有足够的权限来执行插入操作。

    总结

    通过以上步骤逐一排查,应该可以找到导致数据无法插入的原因。如果问题依然存在,请提供更多详细的错误信息或日志输出,以便进一步诊断。

    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 3月4日