You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot新手求教:如何正确实现数据库数据插入?

Spring Boot 实现前端数据插入数据库的正确方式

你已经完成前端数据接收逻辑,接下来要实现数据库插入,需要修正现有代码的问题并完成Service调用,具体步骤如下:

1. 修复 Mapper 的 SQL 语法错误

你的AccApplMapper中INSERT语句缺少右括号,会导致SQL执行失败,修改如下:

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface AccApplMapper {
    // 补上VALUES后的右括号
    @Insert("INSERT INTO ACCT_APPL(ENG_COMP_NAME) VALUES(#{CompanyName})")
    public int addAcctAppl(@Param("CompanyName") String CompanyName);
}

2. 修复 Service 的依赖注入

RegistrationService中的AccApplMapper未注入,会触发空指针异常,需添加@Autowired注解:

package com.example.demo.service;

import com.example.demo.mapper.AccApplMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegistrationService {
    
    // 添加@Autowired完成Mapper注入
    @Autowired
    private AccApplMapper accApplMapper;
    
    public int addAcctAppl(String CompanyName) {
        return accApplMapper.addAcctAppl(CompanyName);
    }
}

3. 在 Controller 中调用 Service 完成数据插入

在RegistrationController中注入RegistrationService,并在接口方法里调用插入逻辑:

package com.example.demo.controller;

import com.example.demo.result.Result;
import com.example.demo.pojo.NewUser;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.service.RegistrationService;

import org.springframework.web.bind.annotation.*;

@RestController
public class RegistrationController {
    
    // 注入RegistrationService
    @Autowired
    private RegistrationService registrationService;
    
    @CrossOrigin
    @PostMapping(value = "api/registration")
    public Result registration(@RequestBody NewUser user) {
        System.out.println(user.getCompanyName());
        // 调用Service插入数据
        int insertCount = registrationService.addAcctAppl(user.getCompanyName());
        // 根据插入结果返回对应状态
        return insertCount > 0 ? new Result(200) : new Result(500, "数据插入失败");
    }
}

4. 补充数据库连接配置(必填)

需要在application.properties(或application.yml)中配置数据库信息,以MySQL为例:

# 数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 替换为你的数据库地址、库名
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
# 数据库账号密码
spring.datasource.username=你的用户名
spring.datasource.password=你的密码

# 可选:开启MyBatis日志,方便调试SQL
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

额外提示

  • 确保数据库中存在ACCT_APPL表,且ENG_COMP_NAME字段存在
  • 可以给NewUser类重写toString()方法,方便日志打印:
@Override
public String toString() {
    return "NewUser{" +
            "CompanyName='" + CompanyName + '\'' +
            '}';
}

内容的提问来源于stack exchange,提问作者Ka hei Tong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:35:30