Как выбрать записи из связанных таблиц ManyToMany

Рейтинг: -1Ответов: 1Опубликовано: 16.06.2023

Две сущности, связаны отношением ManyToMany:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Category {
    @Id
    @GeneratedValue(generator = Constants.ID_GENERATOR)
    protected Long id;

    protected String code;

    @ManyToMany(CascadeType.PERSIST)
    @JoinTable(
        name = "CATEGORY_ITEM",
        joinColumns = @JoinColumn(name = "CATEGORY_ID"),
        inverseJoinColumns = @JoinColumn(name = "ITEM_ID")
    )
    protected Set<Item> items = new HashSet<Item>();

    @Override
    public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       Category category = (Category) o;
      return Objects.equals(code, category.code);
    }
 
    @Override
    public int hashCode() {
       return Objects.hash(code);
    }
}   
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Item {

    @Id
    @GeneratedValue(generator = Constants.ID_GENERATOR)
    protected Long id;

    protected String code;

    @ManyToMany(mappedBy = "items")
    protected Set<Category> categories = new HashSet<Category>();

    @Override
    public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;
       Item item = (Item) o;
      return Objects.equals(code, item.code);
    }
 
    @Override
    public int hashCode() {
       return Objects.hash(code);
    }
}

Я хочу найти список всех объектов items для конкретной категории.

Так мне нужны объекты Item, а эта информация есть только в таблице Category, то написал такой запрос в CategoryRepository:

    @Query("select i from Category c join с.items i where c.code = :code")
    List<Item> findItemsWithCode(@Param("code") String code);    

В результате получаю пустой список.

Хотя если прочитать конкретный объект

Category сategory = CategoryRepository.getId(1);

из из него извлечь список, то данные там есть

assertEquals(сategory.getItems().size(), 2);

Пробовал такой вариант, но все равно получаю пустой список:

@Query("select c.items from Category с i where c.code = :code")
    List<Item> findItemsWithCode(@Param("code") String code);    

Пробовал написать запрос на стороне ItemRepository и тоже пустой список:

 @Query("select i from Item i join i.categories c where c.code = :code")
    List<Item> findItemsWithCode(@Param("code") String code);    

Как мне получить эти данные?

Ответы

▲ 0

Попробуйте так:

@Query("select i from Category c join c.items i where c.code = :code")
List<Item> findItemsWithCode(@Param("code") String code);