Best approach to create different JSON response from same Entity

Viewed 91

I have an entity class User with 20 fields, some of them being confidential fields. I have a controller class, which has a method getUser to fetch all the user from DB and send the JSON respone. Below is the sample code for the same:

@GetMapping("/getUsers")
public UserDT getUsers( Model theModel) {

    List<User> userList;
    userList = userService.findAll();

    return userList;
}

When I run the above code, it returns all the fields from User table/User Entity Class. Instead of sending all the fields, I would like to send selected fields say Field1 to Field5 only.

Ultimate goal is to have multiple views for the same Entity Class. For URL1 I would like to show only field1 to field5 of User table, But for URL2 I would like to show Field9 , Filed15, Field20.

Do I need to create multiple Entity Class for each URL? Please guide me with the best practice to be followed in such scenario.

1 Answers

Assuming you are using Spring Data JPA, use projections.

So create different projections for your different URLs write a method that returns the projection (or a dynamic one as in the documentation).

public interface NamesOnlyProjection {

  String getFirstName();
  String getLastName();

}
public interface UserinfoProjection {

  String getUsername();
  String getPassword();
  String getDepartment();
}

Then in your repository do something like this


public interface PersonRepository extends JpaRepository<Person, Long> {


  <T> List<T> findAll(Class<T> type);

}

Then you can do something like this in your controller/service

@RestController
public class PersonController {

  private final PersonRepository persons;

  @GetMapping("/people/names")
  public List<NamesOnlyProjection> allNames() {
    return persons.findAll(NamesOnlyProjection.class);
  }  

  @GetMapping("/people/users")
  public List<UserinfoProjection> allNames() {
    return persons.findAll(UserinfoProjection.class);
  }  
}
Related