gpt4 book ai didi

java - JPA 对于原始属性也是懒惰的吗?

转载 作者:行者123 更新时间:2023-12-02 02:51:38 25 4
gpt4 key购买 nike

我正在尝试检测代码中的 N+1 问题。我发现的每个问题示例都涉及两个实体,这并不能真正解释这种情况是否也可能发生在单个实体上。

一般的例子是:一辆汽车有很多轮子。对于每辆车,我想要得到每个轮子。

Select * from cars
Select * from wheels where carId=?

List<Car> cars = getCarsFromDB();
for(Car car : cars){
List<Wheel> wheels = car.getWheels(); //Wheels are entities.
}

但是非实体呢?:

List<Car> cars = getCarsFromDB();
for(Car car : cars){
//select car.plate from Car car where car.id = ?
String plate = car.getPlate(); //Plate is just a varchar.
}

JPA 是否也延迟获取非实体?这也是N+1问题吗?

最佳答案

简短的回答,这取决于情况。

如果您没有使用 Hibernate 的字节码增强功能,那么当您加载实体时,任何基本类型的列都会被自动获取,因此它们并不懒惰,也不会引入额外的查询来使其可用。

因此,在您的情况下,当创建 Car 实例时,就会填充车牌。

现在,如果您使用 Hibernate 的字节码增强功能,并且专门将该字段注释为 @Lazy,那么该字段是惰性字段,并且当您访问该字段时会产生数据库查询成本第一次,就像一个懒惰的联想。

在这种情况下,为了避免 N+1 问题(这里 N 是每个惰性注释字段),您可以指定 @LazyGroup 并将多个惰性初始化字段分组在一起这样当访问组中的一个时,其余的将同时加载。

但同样,我上面描述的后一种情况仅适用于您使用字节码增强并且当您明确指定要延迟加载字段时。

JPA 特定

JPA 规范规定如下:

3.2.9:

An entity is considered to be loaded if all attributes with FetchType.EAGER—whether explictly specified or by default—(including relationship and other collection-valued attributes) have been loaded from the database or assigned by the application. Attributes with FetchType.LAZY may or may not have been loaded. The available state of the entity instance and associated instances is as described in section 3.2.7.

An attribute that is an embeddable is considered to be loaded if the embeddable attribute was loaded from the database or assigned by the application, and, if the attribute references an embeddable instance (i.e., is not null), the embeddable instance state is known to be loaded (i.e., all attributes of the embeddable with FetchType.EAGER have been loaded from the database or assigned by the applica- tion).

...

A basic attribute is considered to be loaded if its state has been loaded from the database or assigned by the application.

假设您有一个从数据库加载的 Car 实例(例如,它不是您通过 #getReference() 获取的 Car 实例),基本属性被视为已加载和分配。

关于java - JPA 对于原始属性也是懒惰的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com