0

I've three classes that have nested relationships:

public class Route {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.EAGER)
    private List<Place> places;
}

public class Place {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH, CascadeType.REMOVE}, mappedBy = "place")
    private List<Image> images;
}

public class Image {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = {CascadeType.REFRESH, CascadeType.DETACH})
    private Place place;

}

I need to fetch a pageable list of images by a route id.

Thats my query:

@Repository
public interface ImageRepository extends CrudRepository<Image, Long> {
    @Query("select place.images from Place place where place.id in (select placeD.id from Place placeD where placeD in (select route.places from Route route where route.id = :routeId)) ")
    Page<List> findAllByRouteId(@Param("routeId") Long routeId, Pageable Page);
}

I've tried different combinations but still no result. I'm new to HQL and read a lot of tutorials and as I understood it requires me to write a connected query as it is now.

But it doesn't work. An error it throws:

InvalidDataAccessResourceUsageException: could not prepare statement

How can I fix it? Or at least where should I dig to?

2 Answers 2

1

Try:

@Query("SELECT DISTINCT i 
        FROM Route AS r
           LEFT JOIN r.places AS p
           LEFT JOIN p.images AS i
        WHERE r.id = :routeId)) ")
Sign up to request clarification or add additional context in comments.

1 Comment

It works, thanks! Can you explain it a little? As for dummies) I mean shouldn't it select routes instead of images?
1

You can find more information here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-subqueries

There are some things that we need to take care of when we try to apply raw sql to hibernate.

Other alternative is to simplify the query using JOINs as mentioned.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.