我正在使用基于类的投影和构造函数表达式。这是我的工作中的示例代码:
@Query("select new com.core.data.category.CategoryDto(c.id,c.code,c.externalCode,c.seoMeta, c.createdAt, c.updatedAt,c.parent.code) FROM Category c where c.code = :code")
CategoryDto findCategoryByCode(@Param("code") String code);
这是我的
CategoryDto
的样子:public class CategoryDto implements Serializable {
private Long id;
private String code;
private String externalCode;
private SEOMeta seoMeta;
private CategoryDto parent;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
Map<String, LocCategoryDto> translation;
//constructor based on the requirement
}
这似乎运行良好,除了一个嵌套对象的属性为null
的情况。在我的情况下,如果这是一个根类别,则父属性可以为null
,但似乎使用c.parent.code
会导致问题,整个对象变成null
。有人能帮我解决以下问题吗?
- 有没有办法使用相同的构造函数表达式来处理这种情况?我尝试查看文档,但没有找到细节。
- 我认为另一种选择可能是使用ResultTransformer(它将我的代码绑定到特定的JPA),但我没有找到任何有关如何在Spring JPA中使用它的信息。
更新
我甚至尝试了使用CASE
选项的选项,但似乎对我也不起作用,因为我仍然得到null实体(而数据库中有数据)。这是我尝试的更新代码:
@Query(value = "select new com.core.data.category.CategoryDto(c.id,c.code,c.externalCode,c.seoMeta, c.createdAt, c.updatedAt, " +
"CASE " +
"WHEN c.parent is NULL " +
"THEN NULL " +
"ELSE c.parent.code " +
"END ) " +
"FROM Category c where c.code = :code")
CategoryDto findCategoryByCode(@Param("code") String code);
编辑2 我甚至尝试了使用join,但似乎也不起作用。
更新:我犯了一个愚蠢的错误。使用了简单的join而不是left join导致了这个问题。
ResultTransformer
将使您与Hibernate绑定。您已经通过在许多地方使用它来使用JPA了。 - Jens Schauder