Creating Spring Boot CRUD Rest APIs with Data JPA and JDBC— Part 1
Spring Boot is a highly used and popular framework in Java which is easy to start with and understand as well. In order to get a head start into the framework we will be creating a Spring Boot Application which exposes REST APIs to create, edit, retrieve and delete a user.
Technology Stack
Spring boot framework
Maven 3.6.3
MySQL 8.0.19
Setting up the Project
- Go to https://start.spring.io/
- Choose the Project type depending on what build tool you want to use. We have chosen maven as the build tool.
- Choose the Spring Boot version
- Fill in the Project Metadata info.
- Add the dependencies . In the case of this project we need Spring Web, Spring Data JPA, MySQL Driver.
- Generate the project and import it in your preferred editor
Setting up the Database
- Create database userdb in MySQL
- Create table user
The User Model will contain the following attributes — id, first name, last name, gender and age.
REST API Endpoints
Create User
Method: POST
Endpoint: /users/save-user
Update User
Method: PUT
Endpoint: /users/update-user/{id}
Delete User
Method: DELETE
Endpoint: /users/delete-user/{id}
Get all Users
Method: GET
Endpoint: /users
Get User by Id
Method: GET
Endpoint: /users/{id}
Project Layout and Implementation
- application.properties — This contains configuration of the spring boot project like database properties, port number, etc .
server.port indicates the port number the application will run on
spring.datasource.username and spring.datasource.password indicates the username and password of the database being used.
spring.datasource.url indicates the url of the database
spring.jpa.hibernate.ddl-auto is a Spring Data JPA property which manipulates how the database schema will be transformed on application startup. The values can be create (creates a new schema every time the application is started), create-drop (the schema is dropped once the application is stopped and only created once the application is started again), update (updates the schema in case of any change) and validate (only validates the schema, not making any changes).
spring.jpa.properties.hibernate.dialect property makes hibernate generate better SQL for the database
- ENTITY — The Entity class is mapped to the respective table in the database. It is a bean which represents the table structure.
In the above figure the User entity is mapped to the user table in the database using @Table annotation where the name property specifies the name of the table.
The annotation @Entity annotation specifies the class an an entity bean and defines that a class can be mapped to a table.
The fields of the User class are mapped to the columns of the user table using @Column annotation. In case the name of the field and the column is different, name property can be used to map the field to the differently named column.
@Id annotation specifies the field which will be the primary key of the entity and @GeneratedValue specifies that the field will be automatically generated according to the specified strategy like in the above case the Identity strategy.
- PERSISTENCE LAYER — This layer helps in transforming the business objects to database rows and vice versa, containing the logic to persist data to or retrieve data from the datastore.
We are using Spring Data which simplifies the data access procedure for databases. JPA (Java Persistence API) is a API specification for object relational mapping which maps the objects of a class to rows of a table (in this example — maps User class to user table).
The Repository interface represents the DAO layer which takes care of database operations.
In the above example JpaRepository can carry out basic CRUD operations and also contains API for pagination and sorting without us having to specify the methods separately. With the help of this the boilerplate code written to access data is reduced.
The Entity (User) and the datatype of the primary key (Integer) of the entity ( i.e the field marked with @Id ) are specified as well.
- PRESENTATION LAYER AND SERVICE LAYER
Presentation Layer — This layer contains REST Controllers which expose the REST endpoints to the client , receives the Rest API request, transforms the JSON received by the client to the mapped model object present in the Rest API as parameters. The model object is then transferred to the service layer.
In the above figure UserController annotated with @RestController annotation making it a controller which receives HTTP requests from the client. It returns an object which is directly written into the HTTP response as JSON or XML. The annotation is a combination of @Controller (marks a class as a Spring MVC controller) and @ResponseBody (tells a controller that the returned object returned is to be serialised into JSON and written into HTTP response) annotations.
@RequestMapping maps HTTP requests to the handler classes/methods of REST controllers.
@PostMapping, @GetMapping, @PutMapping, @DeleteMapping annotated methods handle the respective HTTP POST, GET, PUT, DELETE requests matched with given URI expression.
Service Layer — Implements any business logic on the request model and uses the methods exposed by the Data Access Layer.
UserServiceImpl class is the service class which is autowired in UserController. It exposes the methods of the service layer in the controller.
@Service annotation is a specialisation of @Component annotation. It is used to define service-layer classes.
Implementation of REST CRUD APIs
Creating a User
@RequestBody converts the HTTP Request body to java objects using HTTP message converters.
The user object received in createUser method of UserController is then passed to the service layer.
createUser method in UserServiceImpl receives the user object from the controller and saves it in the database using the JpaRepository UserRepo and returns the saved user back to the controller.
Updating a User
@PathVariable annotation binds the request parameter of the handler method to the URI making it dynamic. Hence it is used for data passed in URI. In the above example id is the path variable which can have dynamic values.
The user object along with the id received in updateUser method of UserController is then passed to the service layer.
updateUser method in UserServiceImpl receives the user object and id from the controller, checks if data is present in the database corresponding to that id using findById method of the JpaRepository. If data is present, the user object is copied to the updatedUser object using BeanUtils.copyProperties() and saved in the database corresponding to the id. The updated user is then returned to the controller.
Deleting a User
The id received as the path variable in deleteUser method of UserController is passed to the service layer.
deleteUser method in UserServiceImpl receives the id from the controller, checks if data is present in the database corresponding to that id using findById . If data is present, it is deleted using the delete method of JpaRepository.
Retrieving all Users
getUsers method of UserController calls the service layer method.
getUsers method in UserServiceImpl uses the findAll method of JpaRepository to retrieve all users from the database. The data is then passed back to the controller.
Retrieving a User by ID
The id received as the path variable in getUserById method of UserController is passed to the service layer.
getUserById method in UserServiceImpl receives the id from the controller, checks if data is present in the database corresponding to that id using findById and retrieves the user. If user is present, the retrieved user is returned to the controller.
Testing the APIs with Postman
Creating a User
Updating a User
Deleting a User
Retrieving all Users
Retrieving a User by ID
Find the link to complete code here
Find Creating Spring Boot CRUD Rest APIs with Data JPA and JDBC — Part 2 here