gpt4 book ai didi

java - 具有 SqlResultSetMapping 和 native 查询的 JPA 数据存储库

转载 作者:IT老高 更新时间:2023-10-28 13:46:52 28 4
gpt4 key购买 nike

我遇到了以下情况:

我的实体彼此相关,但是我无法使用 JPQL。我被迫使用 native SQL。现在我想将这些结果映射到一个 ValueObject。需要明确的是,我不想获取 Object 数组( List<Object[]> )的列表。我有 6 个实体,我只需要其中的一些列。谁能给我一个关于如何从 native 查询实现这种映射的示例?

Tutorial我经历过的。

我的代码:

@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);
}

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

原因:

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

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

提前致谢!

最佳答案

添加缺少的结果类

@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);

关于java - 具有 SqlResultSetMapping 和 native 查询的 JPA 数据存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171583/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com