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

Spring Boot项目JPA查询报错:实体属性id不存在,请求排查解决

问题排查与解决

核心错误原因

错误提示String类型不存在属性'id';遍历路径:User.email是因为JPA查询方法命名不符合实体字段规则:你的User实体中邮箱字段为email,但UserRepo里定义的方法是findOneByEmailIdAndPassword,JPA会将EmailId解析为email.id,而email是String类型,不存在id属性,因此触发报错。

分步修复方案

1. 修正Repository方法命名

修改UserRepo中的错误方法名,将findOneByEmailIdAndPassword改为findOneByEmailAndPassword,匹配实体的email字段:

@Repository
public interface UserRepo extends JpaRepository<User, Integer> {
    Optional<User> findOneByEmailAndPassword(String email, String password);
    User findByEmail(String email);
}

注:@EnableJpaRepositories应放在Spring Boot启动类上,而非Repository接口,建议移至主启动类。

2. 移除冗余查询并修复密码验证逻辑

在UserServiceImpl的loginUser方法中,已经通过findByEmail获取到用户并验证了密码正确性,无需再次调用查询方法,直接返回结果即可:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private ModelMapper modelMapper;

    // 修复PasswordEncoder注入缺失问题
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public String addUser(UserDto userDto) {
        // 若id为自增主键,无需手动传入,交给JPA自动生成
        User user = new User(
            userDto.getId(),
            userDto.getName(),
            userDto.getEmail(),
            // 新增用户时必须加密密码
            passwordEncoder.encode(userDto.getPassword())
        );
        userRepo.save(user);
        return user.getName();
    }

    @Override
    public LoginMessage loginUser(LoginDto loginDto) {
        User user1 = userRepo.findByEmail(loginDto.getEmail());
        if (user1 != null) {
            Boolean isPwdRight = passwordEncoder.matches(loginDto.getPassword(), user1.getPassword());
            if (isPwdRight) {
                return new LoginMessage("Login Success", true);
            } else {
                return new LoginMessage("Password Not Match", false);
            }
        } else {
            return new LoginMessage("Email not exist", false);
        }
    }   
}

3. 补充PasswordEncoder配置

原代码中passwordEncoder未注入会导致空指针异常,需添加注入注解,同时在配置类中定义PasswordEncoder Bean:

@Configuration
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

4. 检查User实体定义

确保User实体的主键和字段注解正确:

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String email;
    private String password;

    // 构造方法、getter、setter
}

额外优化建议

  • UserController无需注入UserRepo,业务逻辑全部通过UserService处理,符合分层架构规范。
  • 新增用户时必须加密密码,禁止明文存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:17:03