Constantin Müller
Constantin Müller

Reputation: 1290

Spring - RESTful provide different entity representations

In advance, I'm not speaking of Content Negotiation. Let's assume I've a simple JPA entity, by the way it is convertible with a related DTO it doesn't matter.

@Entity
public class User {

    ...
    private String email;
    private String password;
    ...
}

I've a RESTful controller with two different routes, a secured one and a public one.

@RestController
public class UserController {

    ...

    @GetMapping("/public")
    private User publicRoute() {

        return service.getLatestUser();
    }

    @Secured("...")
    @GetMapping("/private")
    private User privateRoute() {

        return service.getLatestUser();
    }
}

For both routes the same entity is returned, but in the first case a public representation, let's say for a user profile, without sensitive stuff like E-Mail and Password should be returned. However in the second case a private representation, let's say for the owner itself, is required.

Is there any elegant way for doing this? I tried it on JSON level with @JsonIgnore but it doesn't worked for me. Also I tried to use Response-Objects, but it results in a lot of boilerplate code! Any suggestions?

See Also: Recommended by Ananthapadmanabhan there already exists some questions/resources about this topic:

Upvotes: 1

Views: 458

Answers (3)

DevApp
DevApp

Reputation: 83

from Question:

  1. In the database table you can have two roles
  2. Say like User and Owner 3.In the service,check if it is user or owner and get the required details then have the two DTOs,for each of their information that you want to send,set the info and return.
  3. Or have a Common DTO, conataining all the information and when want to send user info just ignore the other info{Subset} else all.

Tell me what do you think of this solution?

Upvotes: 0

Ananthapadmanabhan
Ananthapadmanabhan

Reputation: 6216

You could have different DTO objects being returned from the two endpoints instead of returning the same Entity class, that way you can have control over which attributes should be there in the response.

Read here about the advantages of using a DTO .

Another approach that you could make is to have custom serializers and deserializers for your endpoint. You could read here for more details. And here

Upvotes: 2

Ignore dto fields while sending back to controller.

you can write you own method if your object is not final private User ignoreEmailAndPass(User user){User usr=new User();usr.setName();//send only required fields.}

Upvotes: 0

Related Questions