I want to search data in User table by name case insensitive.
@Repository public interface UserRepository extends JpaRepository<User, Long> { @Query("select u from User u where lower(u.name) like %lower(?1)%") public List<User> findByNameFree(String name); }
I got an error: unexpected token: %. Where should I place '%'?
Overview. Spring Data JPA queries, by default, are case-sensitive. In other words, the field value comparisons are case-sensitive.
SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances. For example, a JPQL query can retrieve an entity object rather than field result set from database, as with SQL.
Case Sensitivity. Queries are case-insensitive, except for names of Java classes and properties.
For example, a JPQL query can retrieve and return entity objects rather than just field values from database tables, as with SQL. That makes JPQL more object oriented friendly and easier to use in Java.
You can use the concat operator:
@Query("select u from User u where lower(u.name) like lower(concat('%', ?1,'%'))") public List<User> findByNameFree(String name);
or with a named parameter:
@Query("select u from User u where lower(u.name) like lower(concat('%', :nameToFind,'%'))") public List<User> findByNameFree(@Param("nameToFind") String name);
(Tested with Spring Boot 1.4.3)
If that is only what you want and you are using Spring Data JPA you don't need to write a query.
List<User> findByNameContainingIgnoreCase(String name);
Else you need to wrap the name
attribute with %
before you pass it to the method (putting those directly in the query will simply not work). Or don't use a query but use a specification or the Criteria API to create the query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With