How to perform a query in Spring Data /JPA with a foreign Key?
·
Answer a question
I have a problem where I need to perform a query using a foreign key in the table. The problem is that in the @Query above(made in the ExpenseRepository above) my logs say that is he's not searching by user id(foreign key) but instead he is searching for the primary key of the expense entity class.
This is my User Entity class:
@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
This is my Expenses Entity class:
@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
Finally this is my repository where I do the query itself
public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
@Query("FROM Expenses g where g.id = :userId")
GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);
}
Answers
Use fields, not columns in @Query
public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
@Query("FROM Expenses g where g.user.id = :userId")
GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);
}
更多推荐



所有评论(0)