【问题标题】:spring boot jpa repository interface always returns nullspring boot jpa 存储库接口总是返回 null
【发布时间】:2017-11-21 10:04:10
【问题描述】:

这是我的代码在我的控制器下面,即使我传递了一个有效的密钥,结果我总是得到 null。有人可以告诉我为什么会这样。下面是我的存储库、控制器和域类

public interface AbcRepository extends JpaRepository<ForgotPasswordToken, int> {
    Abc findByHashKey(String hashKey);
    Abc findByUser(User user);
}

映射:

@RequestMapping(value = "/validateKey/{hashKey}", method = RequestMethod.GET)
public ResponseEntity validateKey(@PathVariable String hashKey) {
    Abc abc = AbcRepository.findByHashKey(hashKey);
    if (abc == null) {
        return ResponseEntity.badRequest().body("Invalid key");
    }
    return ResponseEntity.ok().body(abc.getUser());
}

实体:

@Entity
@Data
public class Abc {

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

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;

    private String hashKey;

    private String email;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;

    @PrePersist
    public void onCreate() {
        this.createdAt = new Date();
    }

}

【问题讨论】:

  • 您的存储库返回的是ForgotPasswordToken 而不是Abc,而您的密钥是long 而不是int
  • 或者,您没有任何符合您条件的实体
  • 您好,我尝试了 long 仍然得到相同的结果。我在任何地方都使用 ForgotPasswordToken 而不是 Abc。抱歉在这里复制代码时出错了想要使用 ForgotPasswordToken 的别名所以使用 Abc
  • 我的数据库中确实有匹配的实体
  • Abc 为空,还是您的存储库为空?

标签: java jpa spring-boot repository


【解决方案1】:

您在存储库和 ABC 类中有不同类型的主键。

你应该改变

JpaRepository<ForgotPasswordToken, int> 

JpaRepository<ForgotPasswordToken, Long>

并在 ABC 类中使用 Long id

private Long id;

并且建议使用对象类型作为 JPA @Id 而不是原语。所以把long改成Long

Primitive or wrapper for hibernate primary keys

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 2017-08-06
    • 2018-11-09
    • 2022-10-13
    • 2020-02-25
    • 1970-01-01
    • 2021-11-07
    • 2019-07-12
    • 2019-08-22
    相关资源
    最近更新 更多