How to retrieve a complex class and its members using Hibernate Projection?

前端 未结 4 587
星月不相逢
星月不相逢 2021-01-04 09:08

I have a class as following that need to retrieve from DB using Hibernate. The problem is my class has multiple members and majority of them are classes, how can I retrieve

4条回答
  •  攒了一身酷
    2021-01-04 09:23

    Because you have a List of Courses and a Set of Cars, you can simply fetch the whole graph in a single query:

    select s
    from Student s
    left join fetch s.courses
    left join fetch s.dealer d
    left join fetch d.cars
    where s.id = :id
    

    Because you are fetching two collections, this query will generate a Cartesian Product, so you need to make sure that the selected children collections don't have too many entries.

    If you don;t want to run into a Cartesian product, you can simply run this query:

    select s
    from Student s
    left join fetch s.courses
    left join fetch s.dealer d
    where s.id = :id
    

    and then you access the dealer.cars to fetch that collection with a separate query:

    Student s = ...;
    s.getDealer().getCars().size();
    

提交回复
热议问题