Why @Query are not getting executed in Spring Boot Data JPA?

83 Views Asked by At

I have a Repository:

@Repository
public interface UserRequestRepository extends JpaRepository<UserRequestDao, Long> {

@Query("SELECT ur FROM UserRequestDao ur WHERE ur.user.id = ?1")
    //@Query(value = "SELECT * FROM USER_REQUEST WHERE USER_ID = ?1", nativeQuery = true)
    List<UserRequestDao> findAllByUserId(long id);
}

In both cases (first @Query and the second native @Query) the Hibernate executes the following query:

select v1_0.id,v1_0.cel_id,v1_0.user_id,v1_0.instructions,v1_0.occasion from user_request v1_0

That is to retrieve all user requests. Why is Hibernate ignoring the @Query and why is it retrieving all records, when I added the @Query annotation? It should retrieve the records based on the user id.

Here is the DAO object:

@Data
@Entity
@Builder
@Table(name = "USER_REQUEST")
@NoArgsConstructor
@AllArgsConstructor
public class UserRequestDao {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private UserDao user;

    @ManyToOne(fetch = FetchType.LAZY)
    private CelebDao celeb;

    private String occasion;
    private String instructions;
}

Here is the service class from where I'm calling the repository method:

@Override
public List<VideoRequest> getAllByUserId(Long id) {
    List<VideoRequestDao> videoRequests = repository.findAllByUserId(userService.get(id).getId());
    return videoRequests.stream().map(ObjectConverter::convertToVideoRequestModel).toList();
}

I have tried to figure it out mostly by searching online but could not find a solution.

Any ideas? Thanks

1

There are 1 best solutions below

3
Sairam Nagaraj On

There seems to be no mistake in the @Query implementation, so my guess is, on the @Service layer, you must have called the findAll() method instead of findAllByUserId(long id).