0

I am very new to DTO,
In my project, I have a database with a Team table (team_id, team_name) and User table (..., team_id) . Relation : a Team can have many users. a user belongs only to one team. In my classes I added a Team team attribut in the User entity and I did some joining Jpa annotation to both the entities.

    @ManyToOne
    @JoinColumn(name = "id_team")
    private Team team;

When i launch a findall request from my user entity I get in response a json with a team Object.

{
    ...
    "id_team": 1,
    "team": {
        "id": 1,
        "name": "team1"

    }
}

My idea is to get only a the team name in the response object like this :

 {
    ...
    "id_team": 1,
    "team_name": "team1"

}

I tried adding a string attribut to my user class but it tels me that no Column is referenced by this attribut which is reasonable.

Waiting for your suggestions Thank you

Mou
  • 41
  • 1
  • 7
  • You may want to use `@JsonUnwrapped` and `@JsonView` – Lino Jun 22 '18 at 09:13
  • Can you please provide the full code of your entities and how you query it? Thanks. – Simon Martinelli Jun 22 '18 at 09:15
  • Possible duplicate of [can I perform a query inside of JPA entity to get back a single column](https://stackoverflow.com/questions/10451022/can-i-perform-a-query-inside-of-jpa-entity-to-get-back-a-single-column) – RoadEx Jun 22 '18 at 09:17

1 Answers1

2

You could create DTO class, for example UserDTO:

public class UserDTO {
    private String idTeam;
    private String team;

    public UserDTO(String idTeam, String team) {
        this.idTeam = idTeam;
        this.team = team;
    }

    /* getter and setter ommited */
}

Then, create a service to retrieve the data and return it as UserDTO.

public UserDTO convertUser() {
   // The userService is an example.
   User user = userService.findAll();
   return new UserDTO(user.getIdTeam(), user.getTeam().getTeamName());
}

With UserDTO you will have JSON result that you wanted.

Sukma Wardana
  • 540
  • 8
  • 21
  • The idea is to get the response from my User entity, because the angular part of my application communicate with the user class ! – Mou Jun 22 '18 at 09:25
  • Well, it's JPA characteristic to bring all the value from it variable. Sorry the solution that I could think is: whether to use DTO or manipulate the JSON response before sending it to the client. – Sukma Wardana Jun 22 '18 at 09:28
  • Do you know how i can maipulate the JSON from the back? – Mou Jun 22 '18 at 09:37
  • Depend on frameworks or library that you used to return the JSON response, this is an example for using JSON-P from Java EE API: http://www.adam-bien.com/roller/abien/entry/json_is_the_new_dto – Sukma Wardana Jun 22 '18 at 09:44