0

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.

2
  • Your name and location fields do not have a @Column annotation, is that correct?
    – PaulD
    Sep 23, 2020 at 13:38
  • That is because the default naming for those fields matches with my db schema. I tried adding @Column and it doesn't change the behavior. Sep 23, 2020 at 14:48

1 Answer 1

0

Well I found one solution, but not sure if that is the best way to do it. Instead of using the constructor expression in the JPQL I used a (hibernate specific) ResultTransformer.

Code:

public List<DistanceResult> findInDistance(Point center, double radiusMeters) {
    String jpql = "select p, distance(:center, p.location) from Place p where dwithin(:center, p.location, :radiusMeters) = true";

    return (List<DistanceResult>) entityManager.createQuery(jpql)
            .setParameter("center", center)
            .setParameter("radiusMeters", radiusMeters)
            .unwrap(Query.class)
            .setResultTransformer(
                    (ListResultTransformer)
                            (tuple, aliases) -> new DistanceResult(
                                    (Place) tuple[0],
                                    ((Number) tuple[1]).doubleValue()
                            )
            ).getResultList();
}

Beware: ListResultTransformer is part of Vlad Mihalcea's hibernate-types library. (See also: https://vladmihalcea.com/hibernate-resulttransformer/)

Query Log:

select place0_.id as col_0_0_, st_distance(?, place0_.location) as col_1_0_, place0_.id as id1_0_, place0_.location as location2_0_, place0_.name as name3_0_ from places place0_ 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]
1
  • I will not mark my own answer as accepted for now. Hoping for some external input. Sep 24, 2020 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.