NateH06
NateH06

Reputation: 3574

@Query Annotation doesn't fill and execute parameters

I am using the Hibernate JPA with Spring Boot, and I am having a trouble returning results from a CRUDRepository where I have written a custom SQL query using the @Query tag. When I access the DAO and execute the method, it fires fine, but nothing is returned from the query.

public interface ContactRepository extends CrudRepository<Contact, BigInteger> {

    @Query(value ="SELECT * FROM all_contacts ac WHERE ac.userid= :userId " +
          "AND LOWER(ac.city) LIKE CONCAT('%', LOWER(:city), '%')",
          nativeQuery=true)
    List<Contact> findAllUserContactsByCityPartialMatch(@Param("city") String city, @Param("userId") BigInteger userId);

}

and when I fire off the code in a Model or Controller somewhere:

@Autowired
ContactRepository contactDAO

List<Contact> results = contactDAO.findAllUserContactsByCityPartialMatch("Chicago", 12345);

results will always be empty

My Logger tells me it's firing off this query:

SELECT * FROM all_contacts ac 
WHERE ac.userid= ? AND LOWER(ac.city) LIKE CONCAT('%', LOWER(?), '%')

I know the query is fine, because when I run the query and fill the fields manually in MySQL terminal, I get a result back.

SELECT * FROM all_contacts ac
WHERE ac.userid= 12345 AND LOWER(ac.city) LIKE CONCAT('%', LOWER("Chicago"), '%')`

Also, I know the DB is configured properly, because if I run say

Iterable<Contact> contactItr = contactDAO.findAll();

in the same model which was mentioned earlier, I get several persisted results back from the DB.

My thought is that it's not filling the parameters or executing them with the parameters in the CRUDRepository class, but I'm not sure. Any thoughts? Thanks!

Upvotes: 0

Views: 575

Answers (1)

veljkost
veljkost

Reputation: 1932

Named parameters are not supported in a native query in JPA. You can use positional parameters.

Also you could make use of JPA query language without @Query at all, something like:

public interface ContactRepository extends CrudRepository<Contact, BigInteger> {

    List<Contact> findAllByCityContainingIgnoreCaseAndUserId(String city, BigInteger userId);

}

Upvotes: 1

Related Questions