QueryDsl 投影将字段留空

问题描述

@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();

这只有两种方式:

  • with qDoc.idid 存在,documentConfiguration 为空
  • 没有 qDoc.idid 为空,documentConfiguration 存在

为什么?

我已经检查过的:当我在 Postgres 客户端中运行 Hibernate 查询时,它总是带来 documentConfiguration 字段。 Bot documentMetadata 在这两种情况下都存在。

解决方法

问题没有解决,但我通过从组合中删除 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());

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...