Table of contents
1.
Introduction
2.
Process behind Updating GET Methods on User Resource to Use JPA
2.1.
Step 1: Creating data Entities
2.2.
Step 2: Connecting the services to use JPA
2.3.
Step 3: Create dao services that will interact with our repository
2.4.
Step 4: Creating controllers to access the service
2.5.
Step 5: Running the service
3.
Frequently Asked Questions
3.1.
What are Restful Web Services?
3.2.
Define the interface of Java RESTful Web Services API.
3.3.
List some important Annotations in context to Restful Web Services and JAX-RS API.
3.4.
Explain how JPA entity objects are retrieved/updated using GET reference.
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Updating GET Methods on User Resource to Use JPA

Author Muskan Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we are going to look at how you can update your GET methods on a User Resource so that we use a JPA instead of basicQuery() and dynamicQuery(). In addition to updating these methods with new code, we also have to update their return type, add a new argument, and change all instances of dynamicQuery() to new ReadEND class methods.                

Updating GET Methods on User Resource to Use JPA

Process behind Updating GET Methods on User Resource to Use JPA

Let’s decode the process involved in Updating GET Methods on User Resources for the Spring Data JPA module.

Step 1: Creating data Entities

  • Create a User class and @Entity annotation to represent this as a model/entity.
     
  • Add getters and setters to the User class.
     
  • Add toString() method to the User class. (Optional but better to have)
     

User.java

package com.example.starterProjectUsingMySql.model;

import javax.persistence.*;

@Entity
public class User {
   @Id
   @GeneratedValue(strategy= GenerationType.AUTO)
   private Integer id;

   private String firstName;

   private String lastName;

   private String email;

   private String address;

   //default constructor
   protected User() {

   }

   public User(Integer id, String firstName, String lastName, String email, String address) {
       super();
       this.id = id;
       this.firstName = firstName;
       this.lastName = lastName;
       this.email = email;
       this.address = address;
   }


   public Integer getId() {
       return id;
   }


   public void setId(Integer id) {
       this.id = id;
   }


   public String getFirstName() {
       return firstName;
   }


   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }


   public String getLastName() {
       return lastName;
   }


   public void setLastName(String lastName) {
       this.lastName = lastName;
   }


   public String getEmail() {
       return email;
   }


   public void setEmail(String email) {
       this.email = email;
   }


   public String getAddress() {
       return address;
   }


   public void setAddress(String address) {
       this.address = address;
   }


   @Override
   public String toString() {
       return String.format("User [id=%s, firstName=%s, lastName=%s email=%s address=%s]", id, firstName, lastName, email, address);
   }

}
You can also try this code with Online Java Compiler
Run Code

Step 2: Connecting the services to use JPA

  • Create a UserRepository class.
     
  • Let UserRepository extend JpaRepository<User, Integer>.
     

You will have to specify the entity that needs to be managed by JPARepository in <>.
 

UserRepository.java

package com.example.starterProjectUsingMySql;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {

}
You can also try this code with Online Java Compiler
Run Code

Step 3: Create dao services that will interact with our repository

  • Create a UserDao interface. (The controller is directly going to call the methods defined in the interface, this will add the layer of abstraction above our direct logic)
     
  • Create a UserDaoImpl class. 
     
  • Let the UserDaoImpl implement UserDao.
     
  • Add @Service annotation to UserDaoImpl to represent that these are service providers.
     
  • Add the following methods to the UserDao.
    • User saveUser(User user): To save the user to the DB
       
    • List<User> getAllUsers(): To get all the users from the DB
       
    • void deleteUser(Integer id): To delete the user
       
    • Optional<User> getUser(Integer id) throws Exception: To get the user by id.
       

UserDao.java

package com.example.starterProjectUsingMySql.service;
import com.example.starterProjectUsingMySql.model.User;

import java.util.List;
import java.util.Optional;

public interface UserDao {

   public User saveUser(User user);
   
   public List<User> getAllUsers();
   
   public void deleteUser(Integer id);
   
   public Optional<User> getUser(Integer id) throws Exception;

}
You can also try this code with Online Java Compiler
Run Code

 

UserDaoImpl.java

package com.example.starterProjectUsingMySql.service;

import com.example.starterProjectUsingMySql.repository.UserRepository;
import com.example.starterProjectUsingMySql.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserDaoImpl implements UserDao {

   @Autowired
   private UserRepository userRepository;

   @Override
   public User saveUser(User user) {
       return userRepository.save(user);
   }

   @Override
   public List<User> getAllUsers() {
       return userRepository.findAll();
   }

   @Override
   public void deleteUser(Integer id) {
       userRepository.deleteById(id);
   }

   @Override
   public Optional<User> getUser(Integer id) throws Exception {
       Optional<User> user = userRepository.findById(id);
       if(!user.isPresent()) {
           throw new Exception("User not found");
       }

       return user;
   }

}
You can also try this code with Online Java Compiler
Run Code

Step 4: Creating controllers to access the service

  • Create a UserController.class and add the following endpoints
    • /addUser: to add a new user
       
    • /user/all: to get all the users
       
    • /user/{id}: to get details of a particular user
       
    • /user/delete/{id}: to delete a user by id.
       
package com.example.starterProjectUsingMySql.controller;

import com.example.starterProjectUsingMySql.service.UserDao;
import com.example.starterProjectUsingMySql.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Optional;


@RestController
public class UserController {


   @Autowired
   private UserDao userDaoService;


   @PostMapping(
       path = "/addUser",
       consumes = MediaType.APPLICATION_JSON_VALUE,
       produces = MediaType.APPLICATION_JSON_VALUE
   )
   public ResponseEntity<User> addNewUser(@RequestBody User user) {


       User savedUser = userDaoService.saveUser(user);
       return ResponseEntity.ok().body(savedUser);
   }


   @GetMapping(path = "/user/all")
   public ResponseEntity<List<User>> getAllUsers() {
       return  ResponseEntity.ok().body(userDaoService.getAllUsers());
   }


   @GetMapping(path = "/user/{id}")
   public ResponseEntity<Optional<User>> getUserById(@PathVariable Integer id) {
       try{
           return ResponseEntity.ok().body(userDaoService.getUser(id));
       } catch (Exception e) {
           return ResponseEntity.badRequest().body(null);
       }


   }


   @DeleteMapping(path = "/user/delete/{id}")
   public ResponseEntity deleteUser(@PathVariable Integer id) {
       userDaoService.deleteUser(id);
       return  ResponseEntity.ok().body("User deleted");
   }

}
You can also try this code with Online Java Compiler
Run Code

Step 5: Running the service

  • Build and run the project
     
Running the service
  • Open postman and add the URL http://localhost:8080/addUser to add the user. Choose Post as the HTTP method. Select body, then select raw, and then select JSON from the dropdown. Add the following JSON and send the request. 
     
{
   "firstName": "Muskan",
   "lastName": "Singh",
   "email": "muskansingh@gmail.com",
   "address": "temp address"
}
postman screenshot
postman screenshot

You can add more users in a similar way. To see if the user is saved or not, in the new tab, add the URL http://localhost:8080/user/all and HTTP method as GET and send the request.

postman screenshot

To get the details of a particular user, navigate to http://localhost:8080/user/19 where 19 is the user id, and send a get request.

postman screenshot

To delete a user, navigate to http://localhost:8080/user/delete/19 and send a delete request. Navigate back to http://localhost:8080/user/all and see if you get the user with id 19 in the list or not. 

postman screenshot
postman screenshot

Try it yourself: Navigate to http://localhost:8080/user/19, and what do you get!!!. Also, go through the database to check the result of each request.

Frequently Asked Questions

What are Restful Web Services?

Web services are resources in the stateless client-server architecture known as restful web services, and they can be recognised by their URIs. HTTP GET/POST methods can be used by REST Client applications to call Restful web services. Although REST doesn't define a particular protocol to utilize, it's almost always done so over HTTP/HTTPS. 

Define the interface of Java RESTful Web Services API.

The Java API used to develop RESTful web services is known as JAX-RS. Web service development and deployment are made easier by JAX-RS using annotations. Because JAX-RS is a component of JDK, its annotations can be used without any additional code.

List some important Annotations in context to Restful Web Services and JAX-RS API.

A few significant JAX-RS annotations are indication of the relative path of a class and its methods, using @Path. By looking via the Path annotation value, we can discover a webservice's URI. To specify the HTTP request type for a method, use @GET, @PUT, @POST, @DELETE, and @HEAD. Specify the request and response types using the @Produces and @Consumes annotations.

Explain how JPA entity objects are retrieved/updated using GET reference.

The getReference method functions similarly to the find method with the exception that a hollow object may be returned if the entity object is not already maintained by the EntityManager (null is never returned). The valid primary key is initialized in a hollow object, but none of its other permanent fields are. 

Conclusion

We have briefly discussed the process involved in Updating GET Methods on User Resource to Use JPA, including the creation of new entities,  connecting the services to use JPA, creating dao services that will interact with our repository, creating controllers to access the service, and finally running the service. We hope that we have helped you gain a better grip on the topic with the help of this article.

Visit our website to read more such blogs. Make sure that you enroll in the courses we provide, take mock tests, solve problems available, and interview puzzles. Also, you can pay attention to interview stuff- interview experiences and an interview bundle for placement preparations. Do upvote our blog to help fellow ninjas grow.

Live masterclass