【发布时间】:2021-01-09 16:59:18
【问题描述】:
首先,我在 (Prevent "n+1 selects" with JPA/Hibernate constructor expression?) 知道类似的问题,但我的情况不同,其他问题没有足够的答案。
我注意到,当我使用 Hibernate 作为我的 JPA 提供程序进行 JPQL 查询时,我尝试将实体包装在 DTO 通过使用构造函数表达式,Hibernate 似乎只选择实体的 ID,这会导致 N+1 查询以获取其余属性。
休眠版本: 5.4.21.Final
查询:
select new com.example.DistanceResult(p, distance(:center, p.location)) from Place p where dwithin(:center, p.location, :radiusMeters) = true
查询日志:
select place1_.id as col_0_0_, st_distance(?, place0_.location) as col_1_0_ from places place0_ inner join places place1_ on (place0_.id=place1_.id) where st_dwithin(?, place0_.location, ?)=true
binding parameter [1] as [OTHER] - [POINT (10.90943 48.37102)]
binding parameter [2] as [OTHER] - [POINT (10.90943 48.37102)]
binding parameter [3] as [DOUBLE] - [2000.0]
select place0_.id as id1_0_0_, place0_.location as location2_0_0_, place0_.name as name3_0_0_ from places place0_ where place0_.id=?
binding parameter [1] as [BIGINT] - [3]
select place0_.id as id1_0_0_, place0_.location as location2_0_0_, place0_.name as name3_0_0_ from places place0_ where place0_.id=?
binding parameter [1] as [BIGINT] - [4]
如您所见,我正在尝试使用 hibernate-spatial 进行“位于地理点周围的实体”类型的查询,但我认为这与问题无关。如何让 hibernate 选择整个实体,然后将其包装到 DTO 中?我已经尝试过进行 fetch self join,但这没有帮助。
Java 类:(使用 Lombok)
@Value
public class DistanceResult {
Place place;
Double distanceMeters;
}
@NoArgsConstructor
@Getter
@Setter
@ToString
@Entity
@Table(name = "PLACES")
public class Place extends BaseEntity<Long> {
public Place(String name, Point location) {
this.name = name;
this.location = location;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Point location;
}
BaseEntity 几乎是来自 spring-data-jpa 的 AbstractPersistable,没有 ID 定义。
【问题讨论】:
-
您的姓名和位置字段没有
@Column注释,对吗? -
这是因为这些字段的默认命名与我的数据库架构相匹配。我尝试添加 @Column 并没有改变行为。
标签: java hibernate jpa jpql spatial