Return custom object from Spring Data with Native Query

后端 未结 5 2122
一生所求
一生所求 2020-12-10 04:18

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.

My POJ

5条回答
  •  眼角桃花
    2020-12-10 05:01

    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.

    Example:

    @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 {
    

提交回复
热议问题