【发布时间】:2021-08-28 18:30:42
【问题描述】:
我正在使用基于类的投影和构造函数表达式。这是我工作的示例代码
@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 选项的选项,但似乎这对我也不起作用,因为我仍然得到空实体(虽然数据在数据库中可用)。这是我尝试过的更新代码
@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 我也尝试过加入,但这似乎也不起作用。
更新:我犯了一个愚蠢的错误。使用的是简单连接而不是左连接,导致了这个问题。
【问题讨论】:
-
Nitpick:使用
ResultTransformer会将您绑定到 Hibernate。通过到处使用 JPA,您已经与 JPA 绑定了。
标签: hibernate jpa spring-data-jpa jpa-2.0 jpa-2.1