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.

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);
}
}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> {
}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.
-
User saveUser(User user): To save the user to the DB
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;
}
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;
}
}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.
-
/addUser: to add a new user
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");
}
}Step 5: Running the service
-
Build and run the project

-
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"
}


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.

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.

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.


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.




