具有 SqlResultSetMapping 和本机查询的 JPA Data 存储库

我陷入了以下情况:

我的实体彼此相关,但我无法使用JPQL。我被迫使用本机 SQL。现在我想将这些结果映射到值对象。为了清楚起见,我不想获取对象数组()的列表。我有6个实体,我只需要一些列。任何人都可以给我一个例子,说明如何从本机查询实现这样的映射?List<Object[]>

我经历的教程

我的代码:

@SqlResultSetMapping(
    name = "findAllDataMapping",
    classes = @ConstructorResult(
            targetClass = MyVO.class,
            columns = {
                    @ColumnResult(name = "userFirstName"),
                    @ColumnResult(name = "userLastName"),
                    @ColumnResult(name = "id"),
                    @ColumnResult(name = "packageName")
            }
    )
)

@NamedNativeQuery(name = "findAllDataMapping",
    query = "SELECT " +
            "    u.first_name as userFirstName, " +
            "    u.last_name as userLastName, " +
            "    i.id as id, " +
            "    s.title as packageName, " +
            "FROM " +
            "    invoice as i " +
            "JOIN user as u on i.user_id=u.id " +
            "LEFT JOIN subscription_package as s on i.subscription_package_id=s.id " +
            "where  u.param1=:param1 and i.param2=:param2" +
)

public class MyVO {
    private String userFirstName;
    private String userLastName;
    private Long id;
    private String packageName;

    public MyVO (String userFName, String userLName,
            Long id, String packageName) {
        this.userFirstName = userFName;
        this.userLastName = userLName;
        this.id = id;
        this.packageName = packageName;
    }

    // getters & setters
}

在我的 jpa-repository 模块中:

public interface MyRepository extends JpaRepository<MyEntity, Long> {
    List<MyVO> findAllOfMyVO(@Param("param1") String param1, @Param("param2") String param2);
}

关键是我不知道在哪里放置这些注释,所以我可以使用这种映射。在本机查询中,我无法使用 .我得到以下错误:new rs.rado.leo.mypackage.MyVO(...)

引起:

org.springframework.data.mapping.PropertyReferenceException: No property findAllOfMyVO found for type MyEntity!

我想我的问题很清楚。如果没有,请告诉我,以便我可以编辑我的问题。

提前致谢!


答案 1

添加缺少的结果类

@NamedNativeQuery(name = "findAllDataMapping", resultClass = Entity.class, query="sql")

@NamedNativeQuery(name = "findAllDataMapping", resultClass = MyVO.class, resultSetMapping ="findAllDataMapping" query = "sql")

最后调用存储库中的查询

@Query(nativeQuery = true, name = "findAllDataMapping")
List<MyVO> findAllOfMyVO(@Param("param1") String param1, @Param("param2") String param2);

答案 2

您几乎就在那里,但对于以下部分

  1. 整体和必须存在于实体中,而不是值对象中。在你的例子中,它应该在MyEntity类中,而不是MyVO类中。这应该可以解决您的异常。@SqlResultSetMapping@NamedNativeQuery
  2. 这仍然行不通。完成上述操作后,更改以下内容

    @NamedNativeQuery(name = “findAllDataMapping”, to
    @NamedNativeQuery(name = “MyEntity.findAllDataMapping”,

  3. 最后,在某些情况下,您需要明确定义@ColumnResult(name = “userFirstName”)。如果它是一个复杂的字段,如ZonedDateTime或Boolean,你可能必须显式状态@ColumnResult(name = “date_created”, type = ZonedDateTime.class)。

希望有所帮助。


推荐