【问题标题】:Spring data JPA not returning record while same exists in table表中存在相同记录时,Spring数据JPA不返回记录
【发布时间】:2022-01-13 15:27:14
【问题描述】:

我有一个实体 Student,它有一个列名 username。我正在尝试使用以下方法在 studentRepository 中获取学生:

@Query("select x from Student x where x.userName=:userName")
Student findStudentByUserName(@Param("userName")String  userName)

虽然记录存在于表中,但此方法返回 null。为了交叉验证,我执行了由 hiberante 准备的查询,该查询打印在日志中。这按预期返回了预期的记录。

有人可以帮我理解这个问题吗? 谢谢

编辑:按照 cmets 中的要求,共享存储库类

package com.pinelabs.pineklik.repository.lead;

import java.util.List;
import java.util.Set;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
    
    @Query("select x from Student x where x.userName=:userName")
    Student findStudentByUserName(@Param("userName")String  userName);

}

忘了提到这在所有环境中都可以正常工作,但开发/本地机器除外。

解决方案:我的错。我非常荒谬地指出导致问题的本地数据库而不是测试数据库。

【问题讨论】:

  • 你在使用 JPA 吗?你能发布你的存储库类吗?
  • 如果有帮助,下面是导入语句:package com.pinelabs.pineklik.repository.student;导入 java.util.List;导入 java.util.Set;导入 org.springframework.data.domain.Page;导入 org.springframework.data.domain.Pageable;导入 org.springframework.data.jpa.repository.Query;导入 org.springframework.data.repository.query.Param;导入 org.springframework.stereotype.Repository;
  • 我想看看你是如何声明你的存储库类的。如果你愿意,你可以省略这些方法。
  • 用这个更新了问题。请检查

标签: spring spring-boot hibernate spring-data-jpa


【解决方案1】:

删除@Query 并尝试此操作。这是假设Student实体类中有一个String字段userName

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
    
    
    Student findByUserName(String userName);

}

【讨论】:

  • 我忘了提到相同的代码在其他环境中运行良好,但在开发/本地机器上。 :(
  • 任何错误信息?
  • 不,只是查询没有返回任何数据,如果没有返回数据,我有一个检查抛出错误。这就是实施。只是为了方便,我清理了我的项目。没有运气
  • 请告诉我你的实体类
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多