问题描述
@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();
这只有两种方式:
为什么?
我已经检查过的:当我在 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());