Home > other >  Why native query is not working in following second query?
Why native query is not working in following second query?

Time:11-16

In between the two methods, the first method is written down with JPQL and the second method is in native query.

 1.   @Query("select e from Meeting  e where e.meetingName like %:query%" )
    List<Meeting> findByJPQL(@Param("query") String query);

 2.  @Query( nativeQuery = true, value ="select * from meeting as m where m.meeting_name like '%':query'%'" )
    List<Meeting> findByNativeQuery(@Param("query") String query);

The number one has given proper value but number two doesn't, can anybody tell us what is a problem in the second query?

CodePudding user response:

You do not have to escape the :query parameter at all. This is kind-of documented in the docs: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query.advanced-like

@Query(nativeQuery = true, value ="select * from meeting as m where m.meeting_name like %:query%" )
List<Meeting> findByNativeQuery(@Param("query") String query);

The parameter binding for native queries uses similar code that is used for binding JPQL queries.

https://github.com/spring-projects/spring-data-jpa/blob/dccc58040b2eb59f1ed425df491e6de87b130897/src/main/java/org/springframework/data/jpa/repository/query/StringQuery.java#L232

which returns a static class LikeParameterBinding extends ParameterBinding from:

https://github.com/spring-projects/spring-data-jpa/blob/main/src/main/java/org/springframework/data/jpa/repository/query/StringQuery.java#L288

  • Related