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

Spring Boot项目JPARepository的findByUserName返回null问题排查

直接导致findByUserName返回null的核心问题

你输出的Hibernate执行SQL中where user0_.user_name is null,说明传入查询方法的用户名参数本身就是null,根源出在Controller的参数绑定逻辑:

// 错误写法
@GetMapping(value="/user/{username}")
public User findByUsername(String username) {

路径占位符{username}没有和方法参数做绑定,需要给参数添加@PathVariable注解:

// 修正写法
@GetMapping(value="/user/{username}")
public User findByUsername(@PathVariable String username) {

修改后即可正常接收路径传入的用户名,执行查询返回匹配的用户数据。


Spring Security获取登录用户为null的常见原因

  • 你的UserAccountService实现了UserDetailsService接口,但没有实现接口强制要求的loadUserByUsername方法,Spring Security认证流程无法正确加载用户信息,自然无法将用户存入安全上下文。需要在Service中补充该方法:
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUserName(username);
    if (user == null) {
        throw new UsernameNotFoundException("用户不存在");
    }
    // 此处将自定义User实体转换为Spring Security的UserDetails对象,可按需补充权限配置
    return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), new ArrayList<>());
}
  • 你尝试获取登录用户的接口属于匿名可访问路径,安全上下文未存储认证信息,返回自然为null,需要确认该接口在Spring Security配置中属于需要登录才能访问的路径。
  • 登录用户获取写法有误,正确写法参考:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUsername = authentication.getName();
    // 调用findByUserName即可拿到当前登录用户对象
}

其他潜在风险

  • 实体类的Gender属性首字母大写,不符合Java Bean命名规范,会导致Hibernate属性映射异常,建议修改为小写gender,如果数据库字段名不同可额外添加@Column注解指定映射字段。
  • UserAccountRepository中findByUserName返回类型建议改为Optional<User>,避免空指针异常。
  • Service类中定义的bCryptPasswordEncoder没有添加@Autowired注解,后续做密码校验时会抛出空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:45:00