prettyvoid
prettyvoid

Reputation: 3686

Custom SELECT @Query json keys

I'm doing a JPQL query, something like this

@Repository
@Transactional
public interface UserFlightDao extends CrudRepository<UserFlight, Long> {
    @Query("SELECT uf.departureGps, uf.flight.id, uf.flight.flightNumber, uf.flight.airline.name, uf.flight.departureDate, " +
            "uf.flight.departureAirport.name FROM UserFlight uf WHERE user.id=?1")
    List<UserFlight> getUserFlights(Long userId);
}

UserFlight contains a Flight object, I select values from both UserFlight and Flight objects and return them to the user as json.

First thing, I think it's wrong to use List<UserFlight> as the return type (even though it works) because technically I'm not returning full UserFlight objects. Right? Maybe I should switch to List<Object>.

Second thing, I want the json returned to the user to contain key names. Currently I get json that contains an array of the objects, without their respective key names. Response example:

[
  [
    "sdf",
    1,
    234234,
    "American Airline",
    {
      "dayOfMonth": 13,
      "dayOfWeek": "TUESDAY",
      "dayOfYear": 286,
      "monthValue": 10,
      "month": "OCTOBER",
      "year": 2015,
      "hour": 18,
      "minute": 41,
      "nano": 0,
      "second": 39,
      "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
      }
    },
    "dummy airport"
  ],
  [
    "asfsaf",
    1,
    234234,
    "American Airline",
    {
      "dayOfMonth": 13,
      "dayOfWeek": "TUESDAY",
      "dayOfYear": 286,
      "monthValue": 10,
      "month": "OCTOBER",
      "year": 2015,
      "hour": 18,
      "minute": 41,
      "nano": 0,
      "second": 39,
      "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
      }
    },
    "dummy airport"
  ]
]

Any idea how can I get key names along with the values? Should I construct the json manually after receiving the List<Object> from the repository or is there a simpler way?

This is how I call getUserFlights

@RequestMapping(value = "/user_flights", method = RequestMethod.POST) List<UserFlight> getUserFlights() {
        return userFlightDao.getUserFlights(new Long(1));
    }

Upvotes: 2

Views: 794

Answers (1)

Zeus
Zeus

Reputation: 6566

If you need only the subset of the columns as that of the UserFlight, you need to create a lighter version of the Entity UserFlight, name it UserFlightLight. Return this entity for the above query. This may be a little work, but that can really help you to avoid all the other issues you might see for returning Object type.

Upvotes: 2

Related Questions