Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL Like Case Insensitive

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 '%'?

like image 534
windupurnomo Avatar asked May 12 '16 06:05

windupurnomo


People also ask

Is JPQL case-sensitive?

Overview. Spring Data JPA queries, by default, are case-sensitive. In other words, the field value comparisons are case-sensitive.

What is JPQL vs SQL?

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.

Is hibernate case-sensitive?

Case Sensitivity. Queries are case-insensitive, except for names of Java classes and properties.

Is JPQL simpler than SQL?

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.


2 Answers

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)

like image 105
Wim Deblauwe Avatar answered Sep 23 '22 02:09

Wim Deblauwe


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.

like image 42
M. Deinum Avatar answered Sep 22 '22 02:09

M. Deinum