first things first, I know about the similar question at (Prevent "n+1 selects" with JPA/Hibernate constructor expression?) but my case is different and that other question doesn't have any sufficient answer.
I noticed that when I do a JPQL query using Hibernate as my JPA provider and I try to wrap an entity in a DTO by using the constructor expression, Hibernate seems to only select the entity's ID which later on leads to N+1 queries to get the rest of the properties.
Hibernate Version: 5.4.21.Final
The Query:
select new com.example.DistanceResult(p, distance(:center, p.location)) from Place p where dwithin(:center, p.location, :radiusMeters) = true
Query Log:
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]
As you can see I'm trying to do a "entities located around geo point" type of query using hibernate-spatial but I don't think this is related to the problem. How can I tell hibernate to select the whole entity and then wrap it into the DTO? I already tried doing a fetch self join but this didn't help.
Java Classes: (Lombok is used)
@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
is pretty much AbstractPersistable
from spring-data-jpa sans the ID definition.
@Column
annotation, is that correct?