Javatpoint Logo
Javatpoint Logo

Updating GET Methods on User Resource to Use JPA

In this topic, we will create a service that retrieves all the users.

Still, we are using the UserResource, which talks to the in-memory. Now we will create a new UserResource that will talk to the embedded database. Let's create a new user resource.

Step 1: Copy the UserResource.java file and paste it in the user package. Rename it with UserJPAResource.

Step 2: Now, we have two URIs with the same name that create conflict. To remove this conflict, we will add /jpa in UserJPAResource.java file.

UserJPAResource.java

But it is not really talking to the database. We need to create a spring data repository.

Step 3: Create an interface with the name UserRepository that extends JpaRepository. Specify the entity that has to be managed. We have specified User and Integer. Now we have the UserRepository ready.

UserRepository.java

Step 4: Create the use of UserResource. We have autowired the UserRepository interface in the UserJPAResource class.

Step 5: Return the userRepository.findAll() in the retriveAllUsers() method.

The retriveAllUsers() is the only method that retrieve data form the embedded database, all the other methods retrieve data from the static array list.

Step 6: Open the Postman. Type the URI http://localhost:8080/jpa/users and send a GET request. It shows all the data that is fetched from the embedded database.

Updating GET Methods on User Resource to Use JPA

Again send a GET request with the URL http://localhost:8080/jpa/users/1. It returns the specified user id, i.e. 1, but it picks up data from memory.

But we are required to fetch data from the embedded database. We need to change the following services in the UserJPAResource.java.

In the following service, the findById() returns the Option of User whether user is null or not null. Whenever we use findById(), there is two possibilities: id exist or not exist. When it does not exist it comes with a proper object. We will check the user exist or not by the statement if(!user.isPresent()). If the user is not present it throws an exception.

Again send a GET request with the URL http://localhost:8080/jpa/users/1. It returns a specified user and the link to /jpa/users.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA