为了仅收集我需要的数据,我使用以下查询来进行对象声明:
@Query(value = "select d.id as id "
+ " , d.statusChanged as statusChanged "
+ " from Declaration d ",
countQuery="select count(id) from Declaration")
Page<DeclarationIDTO> findAllDeclarationListIDTO(Pageable pageable);
DeclarationIDTO
有一个 getId()
和一个 getStatusChanged()
。
这有效。
现在我想添加自由职业者的 ID,如下所示:
@Query(value = "select d.id as id "
+ " , d.statusChanged as statusChanged "
+ " , f.id as 'freelancer.id' "
+ " from Declaration d join d.freelancer f",
countQuery="select count(id) from Declaration")
Page<DeclarationIDTO> findAllDeclarationListIDTO(Pageable pageable);
DeclarationIDTO
有一个 getFreelancer()
,它有一个 getId()
但我收到错误:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT, found ''freelancer.id'' near line 1, column 66 [select d.id as id , d.statusChanged as statusChanged , f.id as 'freelancer.id' from nl.tibi.sbys.domain.Declaration d join d.freelancer f]
知道如何使用对象链吗?
可能的解决方法:
1)扁平化界面:
@Query(value = "select d.id as id "
+ " , d.statusChanged as statusChanged "
+ " , f.id as 'freelancer_id' "
+ " from Declaration d join d.freelancer f",
countQuery="select count(id) from Declaration")
Page<DeclarationIDTO> findAllDeclarationListIDTO(Pageable pageable);
DeclarationIDTO 将具有 getId()、getStatusChanged() 和 getFreelancer_id()
缺点是界面必须复制所有需要的自由职业者字段,并且我必须使用映射器将 freelancer_id 映射到具有 freelancer.id 的 DTO 对象
2)使用构造函数而不是接口(interface):
@Query(value = "select new DeclarationDTO(d.id "
+ " , d.statusChanged "
+ " , f.id) "
+ " from Declaration d join d.freelancer f",
countQuery="select count(id) from Declaration")
Page<DeclarationDTO> findAllDeclarationListIDTO(Pageable pageable);
缺点是我需要为不同的页面提供许多构造函数,或者需要选择空值来扰乱我的查询
3)每个对象多个查询,这会影响性能并且需要大量工作。
4) 选择完整的子对象:
@Query(value = "select d.id as id "
+ " , d.statusChanged as statusChanged "
+ " , f as freelancer "
+ " from Declaration d join d.freelancer f",
countQuery="select count(id) from Declaration")
Page findAllDeclarationListIDTO(Pageable pageable);
DeclarationIDTO
有一个 getId()
getStatusChanged()
和 getFreelancer()
这项工作仍然收集了许多数据,这对性能来说是一个缺点。
如果有一个简单的解决方案来获取 f.id,它将解决所有缺点。
这里似乎有一个答案:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
什么时候我会调查它。
最佳答案
1) 您的 DeclarationIDTO
必须具有按顺序包含 id 和 statusChange 参数的构造函数
2) 尝试在查询中添加具有完全限定名称的新运算符:
"select new my.package.DeclarationIDTO(d.id as id, d.statusChanged as statusChanged "
+ " , f.id as 'freelancer.id' "
+ " from Declaration d join d.freelancer f",
关于java - Hibernate选择子对象进入界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707125/