Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a query in Spring Data /JPA with a foreign Key?

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

}
like image 365
José Nobre Avatar asked Apr 14 '18 12:04

José Nobre


1 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);
}
like image 53
Bogdan Lukiyanchuk Avatar answered Sep 28 '22 06:09

Bogdan Lukiyanchuk