Search code examples
javahibernatejpaspring-data-jpahql

Spring data jpa not selecting all records


I'm beginner at Hibernate and I wan't to figure out some mechanisms. I have entity:

@Entity
@Table(name = "dish")
public class Dish implements Serializable {

   @ManyToMany(fetch = FetchType.LAZY)
   private List<Ingredient> ingredients;

   @ManyToOne(fetch = FetchType.LAZY)
   private Category category;
}

And repository with such method:

@Query("select d from Dish d join fetch d.ingredients")
    Set<Dish> getDishesWithIngredientsAndCategory();

And I noticed, that I'm retrieving by this method only Dishes, that have associated ingredients. I have no idea how to get all Dishes, even that haven't ingredients? And second question is: is it possible to combine in one @Query fetch two columns? Something like:

@Query("select d from Dish d join fetch d.ingredients, d.category")

I tried to use such query, but I'm receiving QuerySelectionException: "d.category is not mapped".


Solution

  • That I'm retrieving by this method only Dishes, that have associated ingredients.

    Use Left Join instead of join: @Query("select d from Dish d left join fetch d.ingredients")

    And second question is: is it possible to combine in one @Query fetch two columns? You can try this:

    @Query("select d from Dish d join fetch d.ingredients join fetch d.category")