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

13,512

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);
}
Share:
13,512
José Nobre
Author by

José Nobre

Updated on June 13, 2022

Comments

  • José Nobre
    José Nobre almost 2 years

    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);
    
    }
    
  • José Nobre
    José Nobre about 6 years
    Yes that was the problem. I assume that was the problem to. Thank you for the feedback.
  • Ratul Sharker
    Ratul Sharker almost 3 years
    It also does the job, but the problem is, it generates unnecessary ‘left outer join’ even though the userId is present in the expense table.