SpringBoot+Hibernate+Restful : format response

2019-08-28 22:41发布

问题:

I am newbie with Hibernate and trying to create an API which will return current position. So in DaoImpl I write a query

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();
}

In controller

@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);
    }

and when I call that API I receive this response

[[11,"07:30:00",106.634756,10.826307,"2017-11-23"],[15,"07:00:00",106.632142,10.826456,"2017-11-24"]] I just want to ask why I can't get the attribute name. I still don't get it. Is there any one can explain this, and How can I get the attribute name for example ['employeename':11,'time':"07:30:00",'longtitude':106.634756,'latitude':10.826307,'workday':"2017-11-23"] Please help me

回答1:

That's simply: you use projections like l.employee.id.

For this query

select loc from Location loc

or from Location (the same short version)

Hibernate returns List<Location>, but when you begin to use projections, Hibernate returns List<Object[]>. That list you have as a response.

list() returns a simply List (not generic), so you have an unchecked conversion

List<Object[]> -> List<Location>

What can you do

  1. Convert query result to a Map using transformer and return that Map as a result from the endpoint.

  2. Add class LocationDto and map result to the list of DTO using other transformer.

  3. Use a some.package.LocaitionDto constructor directly in the query (don't forget a package, please) (how does the new keyword in hql work?).

Don't forget to add alias to each projection, please.

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