jplandrain jplandrain - 4 years ago 149
Java Question

Spring Data - Multi-column searches

I am using Spring Data for the paging and the sorting. However, I would like to perform multi-columns searches.

Now, I am using the annotation @Query in my repository interface like this:

public interface MyRepository extends PagingAndSortingRepository<Item,Long> {

@Query(value="select mt from MY_TABLE mt where mt.field1 = %searchtext% or mt.field2 = %searchtext% or mt.field3 = %searchtext%")
Page<Item> findByAllColumns(@Param("searchtext") String searchtext, Pageable pageable);


edit: The problem in this solution is in the where clause of the @Query annotation because we have to repeat the exact same searchtext parameter for every column we want to search on (clarification of the question after the comment of Brandon Oakley)

I would like to know if there is another way to do because the number of columns in a table can be high.

Thanks for your help.

Answer Source

You could use specifications. That also gives you more flexibility. You can have one method, but use multiple specifications for a query:

Page<Item> findAll(Specification<T> spec), Pageable pageable);

myRepository.findAll(textInAllColumns(searchText), pageable);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download