0

In spring java especially in JoinColumn, if we do JoinColumn for example JoinColumn(name="guest_id"). Then all guest data will be displayed. Whereas I only want to retrieve only one data, which is the name only.

@Column(name = "guest_id")
private Integer guestId;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "guest_id", insertable = false, updatable = false)
private String guestName;

When a request is made at postman, the result will be like this

    "guestCard": {
        "id": 53,
        "idPic": null,
        "guestType": null,
        "title": "mr",
        "name": "RIKO JANUAR",
        "phoneNumber": "08100000",
        "email": "riko@email.com",
        "gender": "male",
        "bDay": "2019-10-29",
        "nationality": "AF",
        "idCard": "21321131231",
        "validity": "2019-10-29",
        "telpFax": null,
        "address": "bandung",
        "job": "Musician"
    }

What I want is to take and display only one, which is the name. Like this

 "guestCard": {
        "name": "RIKO JANUAR"
    }

I tried it this way but it didn't work

@Column(name = "guest_id")
private Integer guestId;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "name.guest_id", insertable = false, updatable = false) //this is not work
private String guestName;
Jhon Smith
  • 93
  • 12
  • Why don't you add the logic in the code? I assume you are mapping the request in the server side and then retrieve the data from the DB, true? – assaf.gov Nov 19 '19 at 06:50

2 Answers2

1

As i understand you need dto choose what to select from entities. So create a dto and cast to the query result using projections. Refer Spring data projections -

 @Projection(name="DtoProjection", types={Guest.class})
 public interface DtoOnly {

      Integer getGuestId();
      @Value("#{target.guestCard.guestName}")
      String getGuestName();
    }

Another way is to use Constructor in HQL

@Query("SELECT new NewDto(guest.guestID, guest.guestCard.guestName FROM Guest guest)")
    List<NewDto> findAllGuest();
Amit Naik
  • 983
  • 1
  • 5
  • 16
1

Ignore all fields you want to hide by @JsonIgnoreProperties jackson-annotations on the relationship class.

Other solution, create various model class and transfer the fields.

Sopheak
  • 81
  • 4