Trevor_zam
Trevor_zam

Reputation: 455

Named param not being detected

I have a simple query as follows. I get the expected result if I hard code the id value as follows. But it throws IllegalArgumentException exception if I try to get the value from the Param instead. Note that I have tried to use the Param as both long and String and still the same results. Please advise what I am doing wrong. Thanks.

My Query

public interface FeedDetailRepository extends JpaRepository<FeedDetail, Long> {
    @Query("select fd.message from FeedDetail as fd where fd.feedId =: id")
    String custom(@Param("id") long id);
}  

At Controller, if I run the following, I get an exception.

@GetMapping("/something/{id}")
    public String getDetail(@PathVariable long id){
        return feedDetailRepository.custom(id);
    }

But if I hard code the id value as follows, I get the wanted result.

public interface FeedDetailRepository extends JpaRepository<FeedDetail, Long> {
    @Query("select fd.message from FeedDetail as fd where fd.feedId = 4")
    String getDetailBasedOnFeedId(@Param("id") long id);
}

The exception

nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: Named parameter not bound : id

Upvotes: 1

Views: 16831

Answers (3)

Petar Ivanov
Petar Ivanov

Reputation: 91

I had the same issue:

Wrong query:

SELECT * FROM `cars` as c where c.driver_one = :id OR c.driver_two = **:id;**

Correct query:

SELECT * FROM `cars` as c where c.driver_one = :id OR c.driver_two = **:id** 

Upvotes: 0

Abhinav Singhal
Abhinav Singhal

Reputation: 87

This is likely because of the way you have provided space with in the query. My suggestion would be to format the code and in the string quotes use something similar

SELECT fd.message from FeedDetail AS fd where fd.feedId = :id

Upvotes: -1

Emil Hotkowski
Emil Hotkowski

Reputation: 2343

I would change

 @Query("select fd.message from FeedDetail as fd where fd.feedId =: id")

To (difference lies in space)

 @Query("select fd.message from FeedDetail as fd where fd.feedId = :id")

This is a small difference for you but big for Spring. He recognizes a parameter by attaching name to colon like that

:id

For more details refer to the official Spring Data JPA Reference.

Upvotes: 15

Related Questions