Spring Boot @Param Example

1. Introduction

Spring Boot provides a powerful way to customize query methods by using the @Param annotation in repository interfaces. This annotation is used to bind method parameters to the named parameters in your JPQL or SQL queries. It's particularly useful when you're using Spring Data JPA and defining complex queries in the @Query annotation. In this blog post, we'll cover the usage of @Param with an example.

Key Points:

1. @Param is used to bind method parameters to query parameters in JPQL or SQL queries.

2. It is an essential part of creating repository methods with custom queries using the @Query annotation.

3. @Param aids in clarity and readability by explicitly naming query parameters.

4. It is particularly useful when a method has multiple parameters, and the order of the parameters is not immediately clear.

5. @Param can also be used in conjunction with Spring's web @RequestMapping annotations to bind controller method parameters to URI template variables.

2. Implementation Steps

1. Add Spring Data JPA dependency to your project if it's not already included.

2. Create an entity class that will be managed by JPA.

3. Define a repository interface extending one of the Spring Data repository interfaces.

4. Write a custom query using the @Query annotation and bind its parameters with @Param.

5. Use the repository method in a service or controller to invoke the custom query.

3. Implementation Example

// Step 1: Add Spring Data JPA dependency in your Maven or Gradle project

// Step 2: Define an Entity class
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;
    private String author;
    // Standard getters and setters
}

// Step 3: Define a Repository interface
public interface BookRepository extends JpaRepository<Book, Long> {
    // Step 4: Define a custom query using @Query and bind parameters with @Param
    @Query("SELECT b FROM Book b WHERE b.title = :title AND b.author = :author")
    List<Book> findBooksByTitleAndAuthor(@Param("title") String title, @Param("author") String author);
}

// Step 5: Use the repository in a service
@Service
public class BookService {
    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public List<Book> getBooksByTitleAndAuthor(String title, String author) {
        return bookRepository.findBooksByTitleAndAuthor(title, author);
    }
}

// Step 6: Optionally, create a REST Controller to expose the functionality
@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/search")
    public ResponseEntity<List<Book>> findBooks(@RequestParam String title, @RequestParam String author) {
        List<Book> books = bookService.getBooksByTitleAndAuthor(title, author);
        return ResponseEntity.ok(books);
    }
}

// Step 7: Start the Spring Boot application
@SpringBootApplication
public class ParamAnnotationExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ParamAnnotationExampleApplication.class, args);
    }
}

// You can test the application by hitting the endpoint: GET /api/books/search?title=BookTitle&author=AuthorName

Output:

// The output will be a JSON list of books that match the given title and author.
[    {        "id": 1,        "title": "Effective Java",        "author": "Joshua Bloch"    },    {        "id": 2,        "title": "Clean Code",        "author": "Robert C. Martin"    }]

Explanation:

1. @Entity and @Id: Annotations used to declare the Book class as a JPA entity with a primary key.

2. BookRepository: The repository interface that extends JpaRepository for CRUD operations.

3. @Query: This annotation specifies the custom query to select books by title and author.

4. @Param("title") and @Param("author"): These annotations bind the method parameters title and author to the named parameters in the query.

5. BookService: This is a service class that uses the BookRepository to execute the query.

6. @Service: It indicates that BookService is a Spring-managed service bean.

7. BookController: A REST controller that exposes the search operation as an HTTP GET endpoint.

8. @RestController and @RequestMapping: Annotations to mark BookController as a REST controller and to map web requests to handler methods.

9. @GetMapping: Maps HTTP GET requests to the findBooks method.

10. @RequestParam: Indicates that a method parameter should be bound to a web request parameter.

11. ParamAnnotationExampleApplication: The main application class marked with @SpringBootApplication which includes auto-configuration, component scan, etc.

12. SpringApplication.run(): Boots up the Spring Boot application.


Comments