【问题标题】:SpringBoot+Hibernate+Restful : format responseSpring Boot+Hibernate+Restful:格式化响应
【发布时间】:2017-12-12 16:30:41
【问题描述】:

我是 Hibernate 的新手,正在尝试创建一个返回当前位置的 API。 所以在 DaoImpl 我写了一个查询

public List<Location> getCurrentLocation() {

    return sessionFactory.getCurrentSession().createQuery("select l.employee.id, max(l.locationTime) as currentTime, l.longtitude , l.latitude,l.date from Location l group by l.employee.id").list();
}

在控制器中

@RequestMapping(value = "currentLocation", method = RequestMethod.GET)
    public ResponseEntity<List<Location>> getCurrentLocation() {
        List<Location> location;
        try {
            location = locationService.getCurrentLocation();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResponseEntity<List<Location>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<Location>>(location, HttpStatus.OK);
    }

当我调用该 API 时,我会收到此响应

[[11,"07:30:00",106.634756,10.826307,"2017-11-23"],[15,"07:00:00",106.632142,10.826456,"2017-11-24"]] 我只想问为什么我不能得到属性名。我还是不明白。 有没有人可以解释一下,我怎样才能得到属性名称 例如['employeename':11,'time':"07:30:00",'longtitude':106.634756,'latitude':10.826307,'workday':"2017-11-23"] 请帮帮我

【问题讨论】:

    标签: hibernate rest api spring-boot


    【解决方案1】:

    这很简单:您使用 l.employee.id 之类的投影。

    对于这个查询

    select loc from Location loc

    from Location(相同的短版)

    Hibernate 返回List&lt;Location&gt;,但是当您开始使用投影时,Hibernate 返回List&lt;Object[]&gt;。该列表作为您的响应。

    list() 返回一个简单的List(不是通用的),所以你有一个未经检查的转换

    List&lt;Object[]&gt; -&gt; List&lt;Location&gt;

    你能做什么

    1. 使用转换器将查询结果转换为Map,并从端点返回Map

    2. 添加类LocationDto并使用其他转换器将结果映射到DTO列表。

    3. 直接在查询中使用some.package.LocaitionDto 构造函数(请不要忘记包)(how does the new keyword in hql work?)。

    请不要忘记为每个投影添加别名。

    Spring Hibernate get selected columns

    java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to className

    How to transform a flat result set using Hibernate

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2016-01-23
      • 2019-01-19
      • 1970-01-01
      • 2014-04-06
      • 2019-02-07
      相关资源
      最近更新 更多