具有 SqlResultSetMapping 和本机查询的 JPA Data 存储库
2022-09-02 12:34:54
我陷入了以下情况:
我的实体彼此相关,但我无法使用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!
我想我的问题很清楚。如果没有,请告诉我,以便我可以编辑我的问题。
提前致谢!