使用本机查询从 Spring Data 返回自定义对象 [英] Return custom object from Spring Data with Native Query

查看:25
本文介绍了使用本机查询从 Spring Data 返回自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题基于 另一篇文章.如何使用本机查询实现相同的目标?本机查询不允许 JPQL 因此也不允许新实例.

My question is based on another post. How can I achieve the same with a native query? Native queries do not allow JPQL thus do not allow new instances either.

我的 POJO.

class Coordinates {

    private final BigDecimal latitude
    private final BigDecimal longitude

    ...
}

我的数据库表包含城市周长的坐标,所以有三列:city_name、纬度、经度.每个城市都包含很多(实际上是很多)周边坐标,这些坐标将用于在 Google 地图中构建阴影区域.

My database table contains coordinates for cities perimeter, so there are three columns: city_name, latitude, longitude. Each city contains lots (really, LOTS) of perimeter coordinates that will be used to build a shadow area in Google Maps.

我打算在该表上构建一个简单的本机查询,该查询应返回坐标列表.

I intend to build a simple native query on that table that should return a list of coordinates.

推荐答案

另一篇文章.基本上,我使用了 SqlResultSetMappingConstructorResult(没有其他方法),特别注意对上述帖子的已接受答案的评论:您需要添加 @NamedNativeQuery 对所用interface 实体的注释 AND 在实体名称前加上 . 否则不会工作.

Found the answer on another post. Basically I used SqlResultSetMapping along with ConstructorResult (no other way worked out) with a special attention to a comment on the accepted answer of the mentioned post: you need to add the @NamedNativeQuery annotation to the entity of the used interface AND prepend the entity's name with a . otherwise it won't work.

示例:

@Entity
@Table(name = "grupo_setorial")
@SqlResultSetMapping(
        name = "mapeamentoDeQuadrantes",
        classes = {
                @ConstructorResult(
                        targetClass = Coordenada.class,
                        columns = {
                                @ColumnResult(name = "latitude"),
                                @ColumnResult(name = "longitude")
                        }
                )
        }
)
@NamedNativeQuery(
        name = "GrupoCensitario.obterPerimetroDosSetores",
        query = "SELECT latitude as latitude, longitude as longitude FROM coordenadas where id_setor IN (:setores)",
        resultSetMapping = "mapeamentoDeQuadrantes"
)
public class GrupoCensitario {

这篇关于使用本机查询从 Spring Data 返回自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆