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

SpringBoot注册用户失败 数据无法插入PostgreSQL的user_table问题求助

问题排查与修复方案

1. 依赖注入缺失(最可能的直接原因)

你在TwitterController中定义的UserRepository userRepo没有添加@Autowired注解,Spring不会自动注入该实例,调用userRepo.save(user)时会抛出空指针异常,直接导致数据无法入库。
修复方式:给userRepo添加注入注解:

@Autowired
private UserRepository userRepo;

2. 主键没有配置自增策略

你的User实体类主键id仅加了@Id注解,没有配置自增策略,PostgreSQL不会自动生成主键值,插入时会触发主键非空约束报错。
修复方式:给id字段添加自增配置:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

注意要导入javax.persistence.GeneratedValue和javax.persistence.GenerationType包。

3. Spring Security请求拦截

Spring Security默认会拦截所有未授权的POST请求,你如果没有在Security配置类中放开/register、/process_register的访问权限,提交注册表单时会直接被安全框架拦截,根本不会走到你写的注册逻辑里。
修复方式:在你的Spring Security配置类中添加如下放行规则:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/register", "/process_register").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin().loginPage("/login").permitAll();
}

4. 可选优化(不影响插入但不符合规范)

你的HTML表单中多个input使用了重复的id="floatingInput",不符合HTML规范,可修改为不同id对应不同label,避免前端交互异常。

内容的提问来源于stack exchange,提问作者Mugiten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:48:03