Introduction
In this tutorial, we will demonstrate how to integrate Spring Boot 3 with Hibernate 6 for performing CRUD operations. We will use a Book
entity to showcase the CRUD operations and configure a MySQL database for persistence.
Spring Boot 3 and Hibernate 6 Integration
Spring Boot simplifies the integration with Hibernate by including it as part of the spring-boot-starter-data-jpa dependency. This starter pack automatically configures Hibernate as the default JPA implementation, making it unnecessary to add Hibernate separately.
<!-- Spring Boot and Hibernate --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- MySQL database installed and running (or any other relational database)
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
Step 1: Setting Up the Project
1.1 Create a Spring Boot Project
-
Open your IDE and create a new Spring Boot project.
-
Configure the
pom.xml
file with the following content:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>spring-boot-hibernate-example</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <!-- Spring Boot and Hibernate --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.26</version> </dependency> <!-- Spring Boot Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1.2 Configure Application Properties
Create an application.properties
file in the src/main/resources
directory with the following content:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
Replace your_database_name
, your_username
, and your_password
with your MySQL database credentials.
Step 2: Creating the Entity Class
Create a Book
class in the com.example.springboothibernateexample.model
package:
package com.example.springboothibernateexample.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; private double price; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
Step 3: Creating the Repository Interface
Create a repository interface for the Book
entity in the com.example.springboothibernateexample.repository
package:
package com.example.springboothibernateexample.repository; import com.example.springboothibernateexample.model.Book; import org.springframework.data.jpa.repository.JpaRepository; public interface BookRepository extends JpaRepository<Book, Long> { }
Step 4: Creating the Service Class
Create a service class to handle business logic in the com.example.springboothibernateexample.service
package:
package com.example.springboothibernateexample.service; import com.example.springboothibernateexample.model.Book; import com.example.springboothibernateexample.repository.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class BookService { @Autowired private BookRepository bookRepository; public Book saveBook(Book book) { return bookRepository.save(book); } public List<Book> getAllBooks() { return bookRepository.findAll(); } public Optional<Book> getBookById(Long id) { return bookRepository.findById(id); } public Book updateBook(Book book) { return bookRepository.save(book); } public void deleteBook(Long id) { bookRepository.deleteById(id); } }
Step 5: Creating the Controller Class
Create a controller class to handle HTTP requests in the com.example.springboothibernateexample.controller
package:
package com.example.springboothibernateexample.controller; import com.example.springboothibernateexample.model.Book; import com.example.springboothibernateexample.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/books") public class BookController { @Autowired private BookService bookService; @PostMapping public Book createBook(@RequestBody Book book) { return bookService.saveBook(book); } @GetMapping public List<Book> getAllBooks() { return bookService.getAllBooks(); } @GetMapping("/{id}") public ResponseEntity<Book> getBookById(@PathVariable Long id) { return bookService.getBookById(id) .map(book -> ResponseEntity.ok().body(book)) .orElse(ResponseEntity.notFound().build()); } @PutMapping("/{id}") public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) { return bookService.getBookById(id) .map(book -> { book.setTitle(bookDetails.getTitle()); book.setAuthor(bookDetails.getAuthor()); book.setPrice(bookDetails.getPrice()); Book updatedBook = bookService.updateBook(book); return ResponseEntity.ok().body(updatedBook); }).orElse(ResponseEntity.notFound().build()); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteBook(@PathVariable Long id) { return bookService.getBookById(id) .map(book -> { bookService.deleteBook(id); return ResponseEntity.ok().<Void>build(); }).orElse(ResponseEntity.notFound().build()); } }
Step 6: Running the Application
Run the Spring Boot application from your IDE or from the command line using the following command:
mvn spring-boot:run
You can now test the CRUD operations using a REST client (like Postman) or by visiting the endpoints in your web browser.
Conclusion
In this tutorial, we demonstrated how to integrate Spring Boot 3 with Hibernate 6 to perform CRUD operations. Spring Boot simplifies the integration with Hibernate by including it as part of the spring-boot-starter-data-jpa dependency.
Comments
Post a Comment