Добавил все новые поля (departmentId, course) для групп. Добавил логирование для GroupController.java

This commit is contained in:
ProstoDenya01
2026-03-21 10:58:27 +03:00
parent b89d1c7f72
commit c07e49ca98
4 changed files with 139 additions and 33 deletions

View File

@@ -6,6 +6,9 @@ import com.magistr.app.model.EducationForm;
import com.magistr.app.model.StudentGroup; import com.magistr.app.model.StudentGroup;
import com.magistr.app.repository.EducationFormRepository; import com.magistr.app.repository.EducationFormRepository;
import com.magistr.app.repository.GroupRepository; import com.magistr.app.repository.GroupRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -17,6 +20,8 @@ import java.util.Optional;
@RequestMapping("/api/groups") @RequestMapping("/api/groups")
public class GroupController { public class GroupController {
private static final Logger logger = LoggerFactory.getLogger(GroupController.class);
private final GroupRepository groupRepository; private final GroupRepository groupRepository;
private final EducationFormRepository educationFormRepository; private final EducationFormRepository educationFormRepository;
@@ -28,29 +33,64 @@ public class GroupController {
@GetMapping @GetMapping
public List<GroupResponse> getAllGroups() { public List<GroupResponse> getAllGroups() {
return groupRepository.findAll().stream() logger.info("Получен запрос на получение всех групп");
try {
List<StudentGroup> groups = groupRepository.findAll();
List<GroupResponse> response = groups.stream()
.map(g -> new GroupResponse( .map(g -> new GroupResponse(
g.getId(), g.getId(),
g.getName(), g.getName(),
g.getGroupSize(), g.getGroupSize(),
g.getEducationForm().getId(), g.getEducationForm().getId(),
g.getEducationForm().getName())) g.getEducationForm().getName(),
g.getDepartmentId(),
g.getCourse()
))
.toList(); .toList();
logger.info("Получено {} групп", response.size());
return response;
} catch (Exception e) {
logger.error("Ошибка при получении списка групп: {}", e.getMessage(), e);
throw e;
}
} }
@PostMapping @PostMapping
public ResponseEntity<?> createGroup(@RequestBody CreateGroupRequest request) { public ResponseEntity<?> createGroup(@RequestBody CreateGroupRequest request) {
logger.info("Получен запрос на создание новой группы: name = {}, groupSize = {}, educationFormId = {}, departmentId = {}, course = {}",
request.getName(), request.getGroupSize(), request.getEducationFormId(), request.getDepartmentId(), request.getCourse());
try {
if (request.getName() == null || request.getName().isBlank()) { if (request.getName() == null || request.getName().isBlank()) {
return ResponseEntity.badRequest().body(Map.of("message", "Название группы обязательно")); String errorMessage = "Название группы обязательно";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
if (groupRepository.findByName(request.getName().trim()).isPresent()) { if (groupRepository.findByName(request.getName().trim()).isPresent()) {
return ResponseEntity.badRequest().body(Map.of("message", "Группа с таким названием уже существует")); String errorMessage = "Группа с таким названием уже существует";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
if (request.getGroupSize() == null) { if (request.getGroupSize() == null) {
return ResponseEntity.badRequest().body(Map.of("message", "Численность группы обязательна")); String errorMessage = "Численность группы обязательна";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
if (request.getEducationFormId() == null) { if (request.getEducationFormId() == null) {
return ResponseEntity.badRequest().body(Map.of("message", "Форма обучения обязательна")); String errorMessage = "Форма обучения обязательна";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
}
if (request.getDepartmentId() == null || request.getDepartmentId() == 0) {
String errorMessage = "ID кафедры обязателен";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
}
if (request.getCourse() == null || request.getCourse() == 0) {
String errorMessage = "Курс обязателен";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
Optional<EducationForm> efOpt = educationFormRepository.findById(request.getEducationFormId()); Optional<EducationForm> efOpt = educationFormRepository.findById(request.getEducationFormId());
@@ -62,22 +102,36 @@ public class GroupController {
group.setName(request.getName().trim()); group.setName(request.getName().trim());
group.setGroupSize(request.getGroupSize()); group.setGroupSize(request.getGroupSize());
group.setEducationForm(efOpt.get()); group.setEducationForm(efOpt.get());
group.setDepartmentId(request.getDepartmentId());
group.setCourse(request.getCourse());
groupRepository.save(group); groupRepository.save(group);
logger.info("Группа успешно создана с ID - {}", group.getId());
return ResponseEntity.ok(new GroupResponse( return ResponseEntity.ok(new GroupResponse(
group.getId(), group.getId(),
group.getName(), group.getName(),
group.getGroupSize(), group.getGroupSize(),
group.getEducationForm().getId(), group.getEducationForm().getId(),
group.getEducationForm().getName())); group.getEducationForm().getName(),
group.getDepartmentId(),
group.getCourse()));
} catch (Exception e ) {
logger.error("Ошибка при создании группы: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("message", "Произошла ошибка при создании группы: " + e.getMessage()));
}
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public ResponseEntity<?> deleteGroup(@PathVariable Long id) { public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
logger.info("Получен запрос на удаление группы с ID - {}", id);
if (!groupRepository.existsById(id)) { if (!groupRepository.existsById(id)) {
logger.info("Группа с ID - {} не найдена", id);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
groupRepository.deleteById(id); groupRepository.deleteById(id);
logger.info("Группа с ID - {} успешно удалена", id);
return ResponseEntity.ok(Map.of("message", "Группа удалена")); return ResponseEntity.ok(Map.of("message", "Группа удалена"));
} }
} }

View File

@@ -5,6 +5,8 @@ public class CreateGroupRequest {
private String name; private String name;
private Long groupSize; private Long groupSize;
private Long educationFormId; private Long educationFormId;
private Long departmentId;
private Integer course;
public String getName() { public String getName() {
return name; return name;
@@ -29,4 +31,20 @@ public class CreateGroupRequest {
public void setEducationFormId(Long educationFormId) { public void setEducationFormId(Long educationFormId) {
this.educationFormId = educationFormId; this.educationFormId = educationFormId;
} }
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public Integer getCourse() {
return course;
}
public void setCourse(Integer course) {
this.course = course;
}
} }

View File

@@ -7,13 +7,17 @@ public class GroupResponse {
private Long groupSize; private Long groupSize;
private Long educationFormId; private Long educationFormId;
private String educationFormName; private String educationFormName;
private Long departmentId;
private Integer course;
public GroupResponse(Long id, String name, Long groupSize, Long educationFormId, String educationFormName) { public GroupResponse(Long id, String name, Long groupSize, Long educationFormId, String educationFormName, Long departmentId, Integer course) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.groupSize = groupSize; this.groupSize = groupSize;
this.educationFormId = educationFormId; this.educationFormId = educationFormId;
this.educationFormName = educationFormName; this.educationFormName = educationFormName;
this.departmentId = departmentId;
this.course = course;
} }
public Long getId() { public Long getId() {
@@ -35,4 +39,12 @@ public class GroupResponse {
public String getEducationFormName() { public String getEducationFormName() {
return educationFormName; return educationFormName;
} }
public Long getDepartmentId() {
return departmentId;
}
public Integer getCourse() {
return course;
}
} }

View File

@@ -20,6 +20,12 @@ public class StudentGroup {
@JoinColumn(name = "education_form_id", nullable = false) @JoinColumn(name = "education_form_id", nullable = false)
private EducationForm educationForm; private EducationForm educationForm;
@Column(name = "department_id", nullable = false)
private Long departmentId;
@Column(name = "course", nullable = false)
private Integer course;
public StudentGroup() { public StudentGroup() {
} }
@@ -54,4 +60,20 @@ public class StudentGroup {
public void setEducationForm(EducationForm educationForm) { public void setEducationForm(EducationForm educationForm) {
this.educationForm = educationForm; this.educationForm = educationForm;
} }
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public Integer getCourse() {
return course;
}
public void setCourse(Integer course) {
this.course = course;
}
} }