I have such a problem that when calling the GET (getDoctorByName) method for the doctor, I get all the information about the doctor except for the categories field (there are entries in it, but it returns me an empty array). Creating doctor records and categories work and adding a category for a doctor too.
Created data in the database:
What do I need to change or what did I do wrong?
Doctor Entity:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "doctor")
public class Doctor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String password;
@Column(name = "first_name")
private String fname;
@Column(name = "last_name")
private String lname;
private String description;
private String number;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "doctor_category",
joinColumns = @JoinColumn(name = "doctor_id"),
inverseJoinColumns = @JoinColumn(name = "category_id")
)
private Set<Category> categories;
}
Category Entity:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
private Set<Doctor> doctors;
}
Category and Doctor Repository:
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {
List<Category> findByName(String name);
}
@Repository
public interface DoctorRepository extends JpaRepository<Doctor, Long> {
@EntityGraph(attributePaths = "categories")
List<Doctor> findByFnameAndLname(String fname, String lname);
@EntityGraph(attributePaths = "categories")
List<Doctor> findByFname(String fname);
@EntityGraph(attributePaths = "categories")
List<Doctor> findByLname(String lname);
}
Category Service:
@Service
public class CategoryService {
@Autowired
private CategoryRepository categoryRepository;
public Category createCategory(Category category) {
return categoryRepository.save(category);
}
public Category editCategory(Long categoryId, Category myCategory) {
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Категория с id: " + categoryId + " не найден"));
category.setName(myCategory.getName());
categoryRepository.save(category);
return category;
}
public List<Category> getCategoryByName(String name) {
List<Category> categories;
if (name != null) {
categories = categoryRepository.findByName(name);
} else categories = categoryRepository.findAll();
return categories;
}
public HttpStatus deleteCategory(Long categoryId) {
categoryRepository.deleteById(categoryId);
return HttpStatus.OK;
}
}
Doctor Service:
@Service
public class DoctorService {
@Autowired
private DoctorRepository doctorRepository;
@Autowired
private CategoryRepository categoryRepository;
public Doctor createDoctor(Doctor doctor) {
return doctorRepository.save(doctor);
}
public Doctor editDoctor(Long doctorId, Doctor myDoctor) {
Doctor doctor = doctorRepository.findById(doctorId)
.orElseThrow(() -> new ResourceNotFoundException("Доктор с id: " + doctorId + " не найден"));
doctor.setEmail(myDoctor.getEmail());
doctor.setPassword(myDoctor.getPassword());
doctor.setFname(myDoctor.getFname());
doctor.setLname(myDoctor.getLname());
doctor.setDescription(myDoctor.getDescription());
doctor.setNumber(myDoctor.getNumber());
return doctorRepository.save(doctor);
}
public Doctor addCategoryForDoctor(Long doctorId, Long categoryId) {
Doctor doctor = doctorRepository.findById(doctorId)
.orElseThrow(() -> new ResourceNotFoundException("Доктор с id: " + doctorId + " не найден"));
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Категория с id: " + categoryId + " не найден"));
Set<Category> categories = doctor.getCategories();
categories.add(category);
doctor.setCategories(categories);
return doctorRepository.save(doctor);
}
public List<Doctor> getAllDoctors() {
List<Doctor> doctors = doctorRepository.findAll();
for (Doctor doctor : doctors) {
// вызовите getCategories() у каждого доктора, чтобы загрузить связанные категории
doctor.getCategories().size();
}
return doctors;
}
public List<Doctor> getDoctorByName(String fname, String lname) {
List<Doctor> doctors;
if (fname != null && lname != null) {
doctors = doctorRepository.findByFnameAndLname(fname, lname);
} else if (fname != null) {
doctors = doctorRepository.findByFname(fname);
} else if (lname != null) {
doctors = doctorRepository.findByLname(lname);
} else {
doctors = doctorRepository.findAll();
}
return doctors;
}
public HttpStatus deleteDoctor(Long doctorId) {
doctorRepository.deleteById(doctorId);
return HttpStatus.OK;
}
}
Doctor Controller:
@RestController
@RequestMapping("/doctor")
public class DoctorController {
@Autowired
private DoctorService doctorService;
@PostMapping
public ResponseEntity<Doctor> createDoctor(@RequestBody Doctor doctor) {
return ResponseEntity.ok(doctorService.createDoctor(doctor));
}
@PutMapping
public ResponseEntity<Doctor> editDoctor(@RequestParam Long doctorId, @RequestBody Doctor doctor) {
return ResponseEntity.ok(doctorService.editDoctor(doctorId, doctor));
}
@PutMapping("/add/category")
public ResponseEntity<Doctor> addCategoryForDoctor(@RequestParam Long doctorId, @RequestParam Long categoryId) {
return ResponseEntity.ok(doctorService.addCategoryForDoctor(doctorId, categoryId));
}
@GetMapping("/all")
public ResponseEntity<List<Doctor>> get() {
return ResponseEntity.ok(doctorService.getAllDoctors());
}
@GetMapping
public ResponseEntity<List<Doctor>> getDoctorByName(@RequestParam(required = false) String fname,
@RequestParam(required = false) String lname) {
return ResponseEntity.ok(doctorService.getDoctorByName(fname, lname));
}
@DeleteMapping
public ResponseEntity<HttpStatus> deleteDoctor(@RequestParam Long doctorId) {
return ResponseEntity.ok(doctorService.deleteDoctor(doctorId));
}
}
Category Controller:
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@PostMapping
public ResponseEntity<Category> createCategory(@RequestBody Category category) {
return ResponseEntity.ok(categoryService.createCategory(category));
}
@PutMapping
public ResponseEntity<Category> editCategory(@RequestParam Long categoryId, @RequestBody Category category) {
return ResponseEntity.ok(categoryService.editCategory(categoryId, category));
}
@GetMapping
public ResponseEntity<List<Category>> getCategoryByName(@RequestParam(required = false) String name) {
return ResponseEntity.ok(categoryService.getCategoryByName(name));
}
@DeleteMapping
public ResponseEntity<HttpStatus> deleteCategory(@RequestBody Long categoryId) {
return ResponseEntity.ok(categoryService.deleteCategory(categoryId));
}
}