我有一个问题,我需要在表中使用外键执行查询。问题是在上面的@Query(在上面的ExpenseRepository中创建)中,我的日志说他不是按用户ID(外键)搜索,而是搜索费用实体类的主键。
这是我的用户实体类:
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
@NotBlank(message = "Password required")
@Size(min = 6)
private String password;
//getters and setters
这是我的费用实体类:
@Entity
public class Expenses implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long limitValue;
private long spentValue;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private User user;
//getters and setters here
最后,这是我自己进行查询的存储库
public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
@Query("FROM Expenses g where g.id = :userId")
GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);
}
答案 0 :(得分:3)
使用字段,而不是@Query
public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
@Query("FROM Expenses g where g.user.id = :userId")
GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);
}
答案 1 :(得分:0)
您可以像这样在存储库类中添加一个方法:
public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
GestaoGastos findAllByUserId(Long userId);
}