MyBatis: can I map two result columns into single object property?

Viewed 1293

I have a case where I have a table that stores a geo location across two columns, 'latitude' and 'longitude'. When I map my result set to a Java object, I want to group these two columns together and return them as a nested object, but this nested object is not some association (via foreign key) to another table.

So, imagine this query:

SELECT id, name, latitude, longitude 
FROM places
WHERE id = <some_id>

And, I want to map that - ideally using a resultMap in my XML file - to this:

public class Place {
   private Long id;
   private String name;
   private GeoPoint point;

   public Place(Long id, String name, GeoPoint point) {
      this.id = id;
      this.name = name;
      this.point = point;
   }
   ...
}

public class GeoPoint {
   private BigDecimal latitude;
   private BigDecimal longitude;

   public Place(BigDecimal latitude, BigDecimal longitude) {
      this.latitude = latitude;
      this.longitude = longitude;
   }
   ...
}

From what I've read of the documentation, it's not clear whether this is actually possible to achieve in a MyBatis resultMap. The only discussion on nested objects is when those objects are formed from columns returned as part of a join to another table (association or collection) - i.e. there appears to be a need for an ID.

In my case, these columns merely form a nested value object and do not have a unique ID of their own.

Could anyone share a solution to my problem that avoids me having to return HashMap from my mapper rather than a fully constructed object?

0 Answers
Related