无法延迟加载JPA关系

时间:2019-02-17 19:00:10

标签: java database hibernate jpa persistence

我正在与Jhipster合作。我无法懒洋洋地获取客户。

我已经像这样制作了一个JDL ...

 PROPERTY
 id
 ...

 CUSTOMER
 id
 ...

 CUSTOMER_PROPERTY
 id
 customer_id
 property_id
 value

 relationship OneToMany {
    Customer to CustomerProperty                    
 }
 relationship ManyToOne {
    CustomerProperty to Property    
 }

我的域

Customer.java

 @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
 @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
 private Set<CustomerProperty> customerProperties = new HashSet<>();

Property.java      没有映射

CustomerProperty.java

 @ManyToOne
 private Property property;

 @ManyToOne
 @JsonIgnoreProperties("customerProperties")
 private Customer customer;

我已经尝试过显式设置fetch = FetchType.LAZY,但是它始终将完整的Customer对象与所有CustomerProperties List一起提供

我想了解为什么无法获取

1 个答案:

答案 0 :(得分:2)

调试不是评估集合是否已延迟加载的好方法。调试器本身可能会触发初始化。

代替使用调试器,

import DataLoader from "dataloader";
import { AggregationCursor, Collection, ObjectId } from "mongodb";

export default class BaseLoaders<TEntity> {
    private LoaderId: DataLoader<ObjectId, TEntity>;

    public constructor(collection: Collection<TEntity>) {
        this.LoaderId = new DataLoader((keys) => this.BatchId(collection, keys), {
            cacheKeyFn: (key) => key.toHexString(),
        });
    }

    public get id(): DataLoader<ObjectId, TEntity> {
        return this.LoaderId;
    }

    private async BatchId(collection: Collection<TEntity>, keys: ObjectId[]): Promise<TEntity[]> {
        const aggregation: AggregationCursor<TEntity> = collection.aggregate([
            { $match: { _id: { $in: keys } } },
            { $addFields: { __order: { $indexOfArray: [keys, "$_id"] } } },
            { $sort: { __order: 1 } },
            { $project: { __order: 0 } },
        ]);

        return aggregation.toArray();
    }
}

验证它在加载实体后是否已初始化。

如果此方法返回false,但您仍然怀疑集合稍后会初始化,则应该在可能的后续调用(其他位置)中搜索错误。