How to Implement Search in Spring Boot: Simple Guide
To implement search in
Spring Boot, use Spring Data JPA repositories with custom query methods or @Query annotations. Define search methods in your repository interface that accept search parameters and return filtered results from the database.Syntax
In Spring Boot, search is typically done by defining methods in a JpaRepository interface. You can use method names that describe the search criteria or write custom JPQL queries with @Query.
- Method name query: Spring Data parses method names to create queries automatically.
- @Query annotation: Write custom JPQL or SQL queries for complex searches.
java
public interface ProductRepository extends JpaRepository<Product, Long> { List<Product> findByNameContainingIgnoreCase(String name); @Query("SELECT p FROM Product p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%', :keyword, '%'))") List<Product> searchByDescription(@Param("keyword") String keyword); }
Example
This example shows a Spring Boot application with a Product entity and a repository that supports searching products by name or description. The controller exposes a REST endpoint to perform the search.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.persistence.Entity; import javax.persistence.Id; import java.util.List; @SpringBootApplication public class SearchApplication { public static void main(String[] args) { SpringApplication.run(SearchApplication.class, args); } } @Entity class Product { @Id private Long id; private String name; private String description; // Constructors, getters, setters omitted for brevity } interface ProductRepository extends JpaRepository<Product, Long> { List<Product> findByNameContainingIgnoreCase(String name); @Query("SELECT p FROM Product p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%', :keyword, '%'))") List<Product> searchByDescription(@Param("keyword") String keyword); } @RestController class ProductController { private final ProductRepository repository; public ProductController(ProductRepository repository) { this.repository = repository; } @GetMapping("/search") public List<Product> search(@RequestParam(required = false) String name, @RequestParam(required = false) String description) { if (name != null && !name.isEmpty()) { return repository.findByNameContainingIgnoreCase(name); } else if (description != null && !description.isEmpty()) { return repository.searchByDescription(description); } else { return repository.findAll(); } } }
Output
GET /search?name=phone returns list of products with 'phone' in name (case-insensitive)
GET /search?description=wireless returns products with 'wireless' in description
Common Pitfalls
- Not using
ContainingorLikein method names causes exact match only, missing partial matches. - Ignoring case sensitivity can cause missed results; use
IgnoreCaseorLOWER()in queries. - For complex searches, relying only on method names can be limiting; use
@Queryfor flexibility. - Not handling empty or null search parameters can cause errors or return unwanted results.
java
/* Wrong: exact match only, no partial search */ List<Product> findByName(String name); /* Right: partial, case-insensitive search */ List<Product> findByNameContainingIgnoreCase(String name);
Quick Reference
| Feature | Usage Example | Description |
|---|---|---|
| Method Name Query | findByNameContainingIgnoreCase(String name) | Search by name with partial and case-insensitive match |
| @Query Annotation | @Query("SELECT p FROM Product p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%', :keyword, '%'))") | Custom JPQL query for flexible search |
| Handling Null/Empty | if (param != null && !param.isEmpty()) | Check parameters before searching to avoid errors |
| Repository Interface | interface ProductRepository extends JpaRepository | Base interface to enable CRUD and search methods |
Key Takeaways
Use Spring Data JPA repository methods with descriptive names for simple search.
Use @Query annotation for complex or custom search queries.
Include case-insensitive and partial matching for better search results.
Always validate search parameters to avoid errors or unexpected results.
Expose search functionality via REST endpoints for easy client access.