querydsl投影将字段留空

wydwbb8l  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(339)
@Entity
public class DocumentConsolidated {
    @Id private UUID id;

    @OneToOne(fetch = FetchType.EAGER, optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "metadata_id")
    private DocumentMetadata documentMetadata;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "documentConsolidated")
    private DocumentConfiguration documentConfiguration;
}

@Entity
public class DocumentConfiguration {
    @Id private UUID id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private DocumentConsolidated documentConsolidated;
}

// Service code:
QDocumentConsolidated qDoc = QDocumentConsolidated.documentConsolidated;
(JPQLQueryFactory) queryFactory
        .select(Projections.fields(qDoc, /*qDoc.id, */qDoc.documentConfiguration, qDoc.documentMetadata))
        .from(qDoc)
        .innerJoin(qDoc.documentConfiguration)
        .fetch();

这只有两种方式:
具有qdoc.id: id 存在时, documentConfiguration 为空
无qdoc.id: id 为空, documentConfiguration 存在
为什么?
我已经检查过:hibernate查询总是 documentConfiguration 在postgres客户机中运行时的字段。机器人程序 documentMetadata 在两种情况下都存在。

xvw2m8pv

xvw2m8pv1#

问题没有解决,但我通过移除 Projections 从混合中:

// Service code:
QDocumentConsolidated qDoc = QDocumentConsolidated.documentConsolidated;
QDocumentConfiguration qCfg = qDoc.documentConfiguration;
QDocumentMetadata qMeta = qDoc.documentMetadata;

return queryFactory
        .select(qDoc, qCfg, qMeta) // <-- get rid of Projections
        .from(qDoc)
        .innerJoin(qCfg) // <-- manual join on Lazy entity (qMeta is auto-joined)
        .fetch().stream()
        .map(tuple -> { // <-- entity creation, similar with Projections.bean()
            DocumentConsolidated documentConsolidated = Objects.requireNonNull(tuple.get(qDoc));
            documentConsolidated.setDocumentMetadata(tuple.get(qMeta));
            documentConsolidated.setDocumentConfiguration(tuple.get(qCfg));
            return documentConsolidated;
        })
        .collect(Collectors.toList());

相关问题