Create a new Spring Boot project in your favorite IDE, or using the Spring Initializr. Make sure to select the appropriate dependencies for your project, such as Spring Web, Spring Data JPA, and MySQL Driver.
Create a new package named entity
in your project’s source code directory. Create a new class in the entity
package that represents your domain entity. For example, if you are building a product management system, you might create a Product
class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private Double price;
// Getters and setters
}
How to configure Spring Boot to use a MySQL database
In this example, we’ve added the necessary properties to the application.properties
file to configure Spring Boot to use a MySQL database.
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url
specifies the URL of the database, including the protocol (jdbc:mysql://
), the hostname and port number (localhost:3306
), and the database name (mydb
).spring.datasource.username
specifies the username for accessing the database.spring.datasource.password
specifies the password for accessing the database.spring.datasource.driver-class-name
specifies the class name of the MySQL JDBC driver.spring.jpa.hibernate.ddl-auto
specifies the strategy for updating the database schema. In this example, we’ve set it to “update”, which means Hibernate will update the schema automatically based on the entity classes and their mappings.
You can customize these properties based on your database configuration. For example, you may need to change the database URL, username, and password to match your own database configuration.
How to Create Spring Boot DTO Layer
Create a new package named dto
in your project’s source code directory. Create a new class in the dto
package that represents a data transfer object for your domain entity. This DTO class will be used to transfer data between your application’s layers. For example:
public class ProductDto {
private Long id;
private String name;
private String description;
private Double price;
// Getters and setters
}
How to Create Spring Boot Repository Layer
Create a new package named repository
in your project’s source code directory. Create a new interface in the repository
package that extends the Spring Data JPA JpaRepository
interface. This interface will provide the basic CRUD operations for your domain entity. For example:
public interface ProductRepository extends JpaRepository<Product, Long> {
}
How to Create Spring Boot Service Layer
Create a new package named service
in your project’s source code directory. Create a new interface in the service
package that defines the methods that your service layer will provide. For example:
public interface ProductService {
List<ProductDto> getAllProducts();
ProductDto getProductById(Long id);
void saveProduct(ProductDto productDto);
void deleteProduct(Long id);
}
Create a new class in the service
package that implements the ProductService
interface. This class will use the repository to provide the service methods. For example:
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final ModelMapper modelMapper;
public ProductServiceImpl(ProductRepository productRepository, ModelMapper modelMapper) {
this.productRepository = productRepository;
this.modelMapper = modelMapper;
}
@Override
public List<ProductDto> getAllProducts() {
List<Product> products = productRepository.findAll();
return products.stream()
.map(product -> modelMapper.map(product, ProductDto.class))
.collect(Collectors.toList());
}
@Override
public ProductDto getProductById(Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Product with id " + id + " not found"));
return modelMapper.map(product, ProductDto.class);
}
@Override
public void saveProduct(ProductDto productDto) {
Product product = modelMapper.map(productDto, Product.class);
productRepository.save(product);
}
@Override
public void deleteProduct(Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Product with id " + id + " not found"));
productRepository.delete(product);
}
}
How to Create Controller in Spring Boot
Here is an example of a controller that uses the ProductService
to handle REST API requests:
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public List<ProductDto> getAllProducts() {
return productService.getAllProducts();
}
@GetMapping("/{id}")
public ProductDto getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void saveProduct(@RequestBody ProductDto productDto) {
productService.saveProduct(productDto);
}
@PutMapping("/{id}")
public void updateProduct(@PathVariable Long id, @RequestBody ProductDto productDto) {
ProductDto existingProduct = productService.getProductById(id);
if (existingProduct != null) {
productDto.setId(id);
productService.saveProduct(productDto);
}
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
}
In this example, the @RestController
annotation is used to mark the ProductController
class as a controller that handles HTTP requests. The @RequestMapping
annotation is used to specify the base path for the API endpoints.
The controller has methods that correspond to the CRUD operations for the Product
entity. The @GetMapping
annotation is used to handle HTTP GET requests, the @PostMapping
annotation is used to handle HTTP POST requests, and so on. The @RequestBody
annotation is used to deserialize the request body into a ProductDto
object.
The @ResponseStatus
annotation is used to set the HTTP status code for the response, in this case 201 Created
. The @PathVariable
annotation is used to extract a variable from the request URL, in this case the id
parameter.
In the updateProduct
method, the existing ProductDto
is first retrieved using the getProductById
method, and then the id
is set on the incoming ProductDto
. Finally, the saveProduct
method is called to update the product.
Here are some examples of how to test the controller endpoints using Postman
- GET all products:
- Open Postman and create a new request.
- Set the request type to GET.
- Enter the URL
http://localhost:8080/api/products
. - Send the request and verify that the response contains a list of all products.
- GET a single product by ID:
- Open Postman and create a new request.
- Set the request type to GET.
- Enter the URL
http://localhost:8080/api/products/{id}
(replace{id}
with the ID of the product you want to retrieve). - Send the request and verify that the response contains the product with the specified ID.
- POST a new product:
- Open Postman and create a new request.
- Set the request type to POST.
- Enter the URL
http://localhost:8080/api/products
. - In the request body, select the “raw” option and set the content type to “JSON”.
- Enter a JSON object representing the new product, for example:
{
"name": "New Product",
"description": "This is a new product",
"price": 10.99
}
Send the request and verify that the response has a status code of 201 Created.
4. PUT an existing product:
- Open Postman and create a new request.
- Set the request type to PUT.
- Enter the URL
http://localhost:8080/api/products/{id}
(replace{id}
with the ID of the product you want to update). - In the request body, select the “raw” option and set the content type to “JSON”.
- Enter a JSON object representing the updated product, for example:
{
"name": "Updated Product",
"description": "This is an updated product",
"price": 19.99
}
Send the request and verify that the response has a status code of 200 OK.
- DELETE an existing product:
- Open Postman and create a new request.
- Set the request type to DELETE.
- Enter the URL
http://localhost:8080/api/products/{id}
(replace{id}
with the ID of the product you want to delete). - Send the request and verify that the response has a status code of 204 No Content.
How To run a Spring Boot application, you can use the following steps:
- Build the application:
- Open a command prompt or terminal and navigate to the root directory of your project.
- Run the command
mvn clean install
to build the application and generate a JAR file.
- Run the application:
- Run the command
java -jar target/myapp-0.0.1-SNAPSHOT.jar
to start the application. - Spring Boot will start the embedded Tomcat server and deploy the application.
- Run the command
- Test the application:
- Open a web browser or use a tool like Postman to test the API endpoints.
- Use the URL
http://localhost:8080/api/products
to retrieve a list of all products.
That’s it! You should now be able to run and test your Spring Boot application. Note that you may need to modify the steps slightly depending on the specifics of your project setup.