自定义SELECT @Query json键

时间:2015-10-14 16:00:37

标签: hibernate jpa spring-data-jpa spring-data

我正在做一个JPQL查询,就像这样

@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包含Flight个对象,我从UserFlightFlight个对象中选择值,并将它们作为json返回给用户。

首先,我认为使用List<UserFlight>作为返回类型是错误的(即使它有效),因为从技术上讲,我没有返回完整的UserFlight个对象。对?也许我应该切换到List<Object>

第二件事,我希望json返回给用户包含键名。目前我得到的json包含一个对象数组,没有各自的键名。响应示例:

[
  [
    "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"
  ]
]

任何想法如何获得键名和值?我应该在从存储库接收List<Object>之后手动构建json还是有更简单的方法?

这就是我致电getUserFlights

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

1 个答案:

答案 0 :(得分:1)

如果您只需要UserFlight的列子集,则需要创建实体UserFlight的较轻版本,并将其命名为UserFlightLight。返回此实体以进行上述查询。这可能是一项小工作,但这确实可以帮助您避免返回对象类型时可能遇到的所有其他问题。