Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - CrudRepository with Example

CrudRepository is an interface provided by Spring Data JPA to abstract away the data access layer. By using it, developers can perform basic CRUD operations without having to write boilerplate code. CrudRepository comes with several methods out of the box for reading, updating, deleting, and creating records.

Example:

Let's create a simple example using CrudRepository for CRUD operations on an entity named Book.

1. Setup Dependencies:

In your pom.xml:

<!-- Spring Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- In-memory database for demonstration purposes -->
<dependency>
    <groupId>org.h2</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. Entity:

Define a Book entity:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;

    // Getters, Setters, Constructors, etc.
}

3. Repository:

Define a repository using CrudRepository:

public interface BookRepository extends CrudRepository<Book, Long> {
}

Now, the BookRepository inherits methods like save(), findById(), findAll(), delete(), and more from the CrudRepository.

4. Service:

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    public Book createOrUpdateBook(Book book) {
        return bookRepository.save(book);
    }

    public Optional<Book> getBookById(Long id) {
        return bookRepository.findById(id);
    }

    public Iterable<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }
}

5. Controller:

Define a simple controller to expose CRUD operations:

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Book createOrUpdateBook(@RequestBody Book book) {
        return bookService.createOrUpdateBook(book);
    }

    @GetMapping("/{id}")
    public Optional<Book> getBookById(@PathVariable Long id) {
        return bookService.getBookById(id);
    }

    @GetMapping
    public Iterable<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
    }
}

Now you have a complete example of how to use CrudRepository in a Spring Boot application. Run your application and test the endpoints; they will perform CRUD operations on the in-memory H2 database.

Note: In real-world scenarios, you would likely use a persistent database and configure it in the application.properties or application.yml file.

  1. Using CrudRepository for CRUD operations in Spring Boot:

    • Create a repository interface by extending CrudRepository and use it to perform basic CRUD operations.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          // No need to implement basic CRUD methods
      }
      
  2. Custom queries with CrudRepository in Spring Boot:

    • Define custom query methods in the repository interface using the @Query annotation or method naming conventions.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          @Query("SELECT u FROM User u WHERE u.age > :age")
          List<User> findByAgeGreaterThan(@Param("age") int age);
      }
      
  3. Sorting and pagination with CrudRepository in Spring Boot:

    • Use Sort and Pageable parameters in query methods for sorting and pagination.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          List<User> findByAgeGreaterThan(int age, Sort sort);
          Page<User> findByAgeGreaterThan(int age, Pageable pageable);
      }
      
  4. Defining custom methods in CrudRepository interfaces in Spring Boot:

    • Define custom methods in the repository interface, and Spring Data JPA will automatically generate queries.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          List<User> findByNameAndAge(String name, int age);
      }
      
  5. Query derivation in Spring Boot CrudRepository:

    • Spring Data JPA derives query methods from method names following naming conventions.
    • Example:
      public interface UserRepository extends CrudRepository<User, Long> {
          List<User> findByLastName(String lastName);
      }
      
  6. Using JPA annotations with CrudRepository in Spring Boot:

    • Annotate the entity class with JPA annotations for entity mapping and relationships.
    • Example:
      @Entity
      public class User {
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
          // Other fields and annotations
      }
      
  7. Transactional behavior with CrudRepository in Spring Boot:

    • CrudRepository methods are transactional by default. Use @Transactional for custom transactional methods.
    • Example:
      @Transactional
      public void customTransactionalMethod() {
          // Perform transactional operations
      }