仅收集我需要的数据,我对对象声明使用以下查询:
@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)使用构造函数而不是接口:
@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")
页面findAllDeclarationListIDTO(Pageable pageable);
DeclarationIDTO具有一个getId()getStatusChanged()和getFreelancer()
此方法仍然可以收集许多数据,这对性能有不利影响。
如果有一个简单的解决方案来获取f.id,它将解决所有弊端。
这里似乎有一个答案:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
时间到时我会调查它。
答案 0 :(得分:1)
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",