[英]Hibernate DTO Projections N+1 queries
刚刚在使用 Hibernate 和 Spring 数据 JPA 时实验了一个有趣的事实。 我有以下设置 DTO 和实体:
@Getter
@Setter
public class ClassDto {
private String id;
private String name;
public ClassDto(Entity e) {
this.id = e.id;
this.name = e.name;
}
public ClassDto(String id, String name) {
this.id = id;
this.name = name;
}
}
@Entity
@Setter
@Getter
public class Entity {
@Id String id;
String name;
}
为什么这个查询被执行了 N+1 次。
select new org.xyz.ClassDto(e) from Entity e
虽然这个实体只解构了一次
select new org.xyz.ClassDto(e.id, e.name) from Entity e
我只想要一个关于地下事物如何运作的合乎逻辑的解释。
谢谢
我猜你正在使用这样的查询:
select new org.xyz.ClassDto(e.toManyAssociation) from Entity e
In this case, Hibernate will pass in a proxy instead of a fully initialized entity, so when you access the data of that object in the constructor, Hibernate will lazy load the object. 您可以通过加入关联并改为传递加入别名来解决此问题。
我想你可能对Blaze-Persistence Entity Views感兴趣。
我创建了该库,以允许在 JPA 模型和自定义接口或抽象 class 定义的模型之间轻松映射,例如 Spring Data Projections on steroids。 这个想法是您以您喜欢的方式定义您的目标结构(域模型),并通过 JPQL 表达式将 map 属性(吸气剂)定义为实体 model。
使用 Blaze-Persistence Entity-Views 的 DTO model 可能如下所示:
@EntityView(Entity.class)
public interface ClassDto {
@IdMapping
Long getId();
String getName();
}
查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。
ClassDto a = entityViewManager.find(entityManager, ClassDto.class, id);
Spring 数据集成允许您几乎像 Spring 数据投影一样使用它: https://persistence.blazebit.com/documentation/entity-view/manual-html/。
Page<ClassDto> findAll(Pageable pageable);
最好的部分是,它只会获取实际需要的 state!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.