Hibernate选择子对象进入接口

问题描述 投票:1回答:1

要收集我需要的数据,我使用以下查询对象声明:

        @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")

Page findAllDeclarationListIDTO(可分页可分页);

DeclarationIDTO有一个getId() getStatusChanged()getFreelancer()

这项工作仍有许多收集的数据,这是性能的下降。

如果有一个简单的解决方案来获得f.id,它将解决所有缺点。

这里似乎有一个答案:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

什么时候我会调查它。

java hibernate jpa
1个回答
1
投票

1)你的DeclarationIDTO必须具有id和statusChange params的构造函数

2)尝试使用完全限定名称在查询中添加new运算符:

"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", 
© www.soinside.com 2019 - 2024. All rights reserved.