Я создал класс Java-сущности для «Категории»:
@Entity
@Table(name="categories")
@Getter @Setter
public class CategoryEntity implements Serializable {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
@Column(length = 30, nullable = false)
private String categoryKeyId;
@Column(nullable = false)
private String name;
//Here mappedBy indicates that the owner is in the other side
@OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade = CascadeType.ALL)
private List<ProductEntity> products = new ArrayList<>();
@ManyToOne
private CategoryEntity parent;
@OneToMany(mappedBy="parent")
private List<CategoryEntity> subCategory;
}
Затем я создал класс репозитория:
@Repository
public interface CategoryRepository extends PagingAndSortingRepository<CategoryEntity, Long> {
Page<CategoryEntity> findBySubCategoryNotNull(Pageable pageableRequest);
}
В моем контроллере
@GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public List<CategoryRest> getTopCategoriesWithSubCategories(@RequestParam(value="page", defaultValue="0") int page, @RequestParam(value="limit", defaultValue="5") int limit) {
List<CategoryRest> returnValue = new ArrayList<>();
List<CategoryDto> categoryDtos = categoryService.getTopCategoriesWithSubCategories(page, limit);
// loop the result
for (CategoryDto categoryDto : categoryDtos) {
CategoryRest categoryRest = new CategoryRest();
ModelMapper modelMapper = new ModelMapper();
categoryRest = modelMapper.map(categoryDto, CategoryRest.class);
returnValue.add(categoryRest);
}
return returnValue;
}
Для этого я использую сервис, который использует метод в сервисе.
@Override
public List<CategoryDto> getTopCategoriesWithSubCategories(int page, int limit) {
List<CategoryDto> returnValue = new ArrayList<>();
if (page > 0) page -= 1;
Pageable pageableRequest = PageRequest.of(page, limit);
Page<CategoryEntity> categoriesPage = categoryRepository.findBySubCategoryNotNull(pageableRequest);
List<CategoryEntity> categoryEntities = categoriesPage.getContent();
for(CategoryEntity categoryEntity: categoryEntities) {
CategoryDto categoryDto = new CategoryDto();
returnValue.add(categoryDto);
}
return returnValue;
}
Мой CategoryRest очень прост:
@Getter @Setter
public class CategoryRest {
// data that is returned when a category is created
private String categoryKeyId;
private String categoryName;
private List<CategoryRest> subCategories;
}
У меня есть 2 проблемы, когда я пытаюсь получить результат. Я получаю нулевые результаты. Что касается получения списка подкатегорий, это должно быть проблема с моей логикой с моим запросом JPA (вероятно)