java - spring boot jpa存储库接口(interface)始终返回null

标签 java jpa spring-boot repository

这是我在 Controller 下面的代码,即使我传递了一个有效的 key ,结果我总是得到 null。有人可以告诉我为什么会发生这种情况。下面是我的存储库、 Controller 和域类

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();
    }

}

最佳答案

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

你应该改变

JpaRepository<ForgotPasswordToken, int> 

JpaRepository<ForgotPasswordToken, Long>

并在 ABC 类中使用Long id

private Long id;

并且建议使用对象类型作为 JPA @Id 而不是基元。因此将 long 更改为 Long

参见Primitive or wrapper for hibernate primary keys

关于java - spring boot jpa存储库接口(interface)始终返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44626322/

相关文章:

java - 在 Tomcat 启动时自动启动 Quarz Scheduler

java - 使用 @Async 时,范围 'request' 对于当前线程不活动

rest - InvalidDefinitionException : Cannot construct instance of `com.vehicle.datatransferobject.VehicleDTO`

java - @RequestMapping java.lang.AssertionError : Status Expected :200 Actual :404

java - 未检测到 KeyEvent.KEYCODE_DPAD_CENTER

java - 为什么不能在循环中隐藏局部变量?

java - 比较 Java 中 Git 分支的基准?

java - 调试 MySQL 字符集错误

java - hibernate中过滤器和标准之间的区别

hibernate - JpaRepository native 查询未检测参数