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

Spring JPA查询无报错但始终返回null问题求助

问题描述

我是Spring和JPA的新手,现遇到如下问题:
我定义了User实体、Credentials实体以及UserRepository,但调用如User user = userRepository.findByCredentials_Username(tweetRequestDto.getCredentials().getUsername());等查询方法时,即使凭据正确且已存在于数据库中,始终返回null,且无任何报错信息。

相关代码

User实体

package com.cooksys.twitter.entities;

import java.sql.Timestamp;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import lombok.NoArgsConstructor;

@Table(name = "user_table")
@Entity
@NoArgsConstructor
@Getter
@Setter
public class User {

    @Id
    @GeneratedValue
    private Long id;
    
    @Embedded
    private Credentials credentials;
    
    @Embedded
    private Profile profile;
    
    @CreationTimestamp
    private Timestamp joined;

    @JsonIgnore
    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
    private List<Tweet> tweets;

    @ManyToMany(mappedBy = "likes")
    private List<Tweet> likedTweets;
    
    @ManyToMany(mappedBy = "following")
    private List<User> followers;

    
    @ManyToMany
    private List<User> following;

    @ManyToMany(mappedBy = "userMentioned")
    private List<Tweet> mentions;

    @Column
    private boolean deleted;
}

Credentials实体

package com.cooksys.twitter.entities;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@Data
@Embeddable
public class Credentials {
    
    @Column(unique=true)
    private String username;
    
    private String password;
}

UserRepository

package com.cooksys.twitter.repositories;

import com.cooksys.twitter.entities.Credentials;
import com.cooksys.twitter.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByCredentials(Credentials credentials);
    User findByCredentials_Username(String username);
    User findByCredentialsUsernameAndPassword(String username, String password);
}

排查与解决步骤

  1. 修正查询方法命名
    Spring Data JPA对嵌入类属性的查询,驼峰式命名更可靠。将findByCredentials_Username改为findByCredentialsUsername,或者直接使用已定义的findByCredentialsUsernameAndPassword测试,确认是否能正常返回结果,排除命名规则适配问题。

  2. 排除已删除用户
    User实体包含deleted字段,若数据库中目标用户的该字段为true,默认查询会包含已删除数据。修改查询方法添加过滤条件:

    User findByCredentialsUsernameAndDeletedFalse(String username);
    

    或使用自定义查询:

    @Query("SELECT u FROM User u WHERE u.credentials.username = :username AND u.deleted = false")
    User findActiveUserByUsername(@Param("username") String username);
    
  3. 确认事务上下文
    在调用查询的业务方法上添加@Transactional注解,确保查询在事务上下文内执行,避免因懒加载或缓存机制导致的数据读取异常。

  4. 校验传入的用户名
    打印tweetRequestDto.getCredentials().getUsername()的实际值,确认与数据库中存储的用户名完全一致(注意数据库的大小写规则:MySQL默认不区分,PostgreSQL默认区分),若存在差异需统一格式。

  5. 检查嵌入属性映射
    确认数据库表user_table中存在username和password列,且列名与实体映射一致(无因@Column配置导致的列名偏差)。

  6. 开启SQL日志排查
    在配置文件中添加SQL日志配置,查看实际执行的SQL语句,直接在数据库客户端执行验证:

    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.format_sql=true
    

    通过生成的SQL可快速定位是查询逻辑问题还是数据本身的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:57:43