@NamedNativeQuery with @SqlResultSetMapping for non-entity

后端 未结 1 1223
借酒劲吻你
借酒劲吻你 2021-02-14 00:47

I have been using this post as an example. I have a complex join query (simplified here). It returns a subset of values from two tables (and a derived column using CASE). I don\

相关标签:
1条回答
  • The @SqlResultSetMapping and @NamedNativeQuery annotations need to be on an @Entity, not on the non-entity POJO.

    If the entity is Foo, then add the annotations as follows:

    @SqlResultSetMapping(
               name="myMapping",
               classes={
                  @ConstructorResult(
                       targetClass=CarLimitDelta.class,
                         columns={
                            @ColumnResult(name="caseCol"),
                            @ColumnResult(name="colA"),
                            @ColumnResult(name="colB"),
                            }
                  )
               }
    )
    @NamedNativeQuery(name="Foo.getCarLimitDelta", 
            resultSetMapping="myMapping", 
            query="...")
    @Entity
    public class Foo {
      ...
    }
    

    Note that the @NamedNativeQuery name is prefixed with the entity name, e.g. Foo.getCarLimitDelta.

    Then add the method to the Foo repository:

    @Repository
    public interface FooRepository extends CrudRepository<Foo, String> {
        List<CarLimitDelta> getCarLimitDelta();
    }
    

    Note that the method name, getCarLimitDelta, matches the @NamedNativeQuery name, minus the prefix.

    0 讨论(0)
提交回复
热议问题