Добавил все новые поля (departmentId, code) для дисциплин. Добавил логирование для SubjectController.java

This commit is contained in:
ProstoDenya01
2026-03-21 11:41:01 +03:00
parent c07e49ca98
commit 49ca2e17b6
5 changed files with 184 additions and 15 deletions

View File

@@ -1,7 +1,13 @@
package com.magistr.app.controller; package com.magistr.app.controller;
import com.magistr.app.dto.CreateSubjectRequest;
import com.magistr.app.dto.SubjectResponse;
import com.magistr.app.model.Subject; import com.magistr.app.model.Subject;
import com.magistr.app.repository.SubjectRepository; import com.magistr.app.repository.SubjectRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -12,6 +18,8 @@ import java.util.Map;
@RequestMapping("/api/subjects") @RequestMapping("/api/subjects")
public class SubjectController { public class SubjectController {
private static final Logger logger = LoggerFactory.getLogger(SubjectController.class);
private final SubjectRepository subjectRepository; private final SubjectRepository subjectRepository;
public SubjectController(SubjectRepository subjectRepository) { public SubjectController(SubjectRepository subjectRepository) {
@@ -20,32 +28,84 @@ public class SubjectController {
@GetMapping @GetMapping
public List<Subject> getAllSubjects() { public List<Subject> getAllSubjects() {
return subjectRepository.findAll(); logger.info("Получен запрос на получение всех дисциплин");
try {
List<Subject> subjects = subjectRepository.findAll();
List<Subject> response = subjects.stream()
.map(s -> new Subject(
s.getId(),
s.getName(),
s.getCode(),
s.getDepartmentId()
))
.toList();
logger.info("Получено {} дисциплин", response.size());
return response;
} catch (Exception e) {
logger.error("Ошибка при получении списка дисциплин: {}", e.getMessage(), e);
throw e;
}
} }
@PostMapping @PostMapping
public ResponseEntity<?> createSubject(@RequestBody Map<String, String> request) { public ResponseEntity<?> createSubject(@RequestBody CreateSubjectRequest request) {
String name = request.get("name"); logger.info("Получен запрос на создание дисциплины: name = {}, code = {}, departmentId = {}",
if (name == null || name.isBlank()) { request.getName(), request.getCode(), request.getDepartmentId());
return ResponseEntity.badRequest().body(Map.of("message", "Название обязательно"));
try {
if (request.getName() == null || request.getName().isBlank()) {
String errorMessage = "Название обязательно";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
if (subjectRepository.findByName(name.trim()).isPresent()) { if (subjectRepository.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.getCode() == null || request.getCode().isBlank()) {
String errorMessage = "Код дисциплины обязателен";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
}
if (request.getDepartmentId() == null || request.getDepartmentId() == 0) {
String errorMessage = "ID кафедры не может быть равен 0 или пустым";
logger.error("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
} }
Subject subject = new Subject(); Subject subject = new Subject();
subject.setName(name.trim()); subject.setName(request.getName());
subject.setCode(request.getCode());
subject.setDepartmentId(request.getDepartmentId());
subjectRepository.save(subject); subjectRepository.save(subject);
return ResponseEntity.ok(subject); logger.info("Дисциплина успешно создана с ID: {}", subject.getId());
return ResponseEntity.ok(
new SubjectResponse(
subject.getId(),
subject.getName(),
subject.getCode(),
subject.getDepartmentId()
)
);
} 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<?> deleteSubject(@PathVariable Long id) { public ResponseEntity<?> deleteSubject(@PathVariable Long id) {
logger.info("Получен запрос на удаление дисциплины с ID: {}", id);
if (!subjectRepository.existsById(id)) { if (!subjectRepository.existsById(id)) {
logger.info("Дисциплина с ID - {} не найдена", id);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
subjectRepository.deleteById(id); subjectRepository.deleteById(id);
logger.info("Дисциплина с ID - {} успешно удалена", id);
return ResponseEntity.ok(Map.of("message", "Дисциплина удалена")); return ResponseEntity.ok(Map.of("message", "Дисциплина удалена"));
} }
} }

View File

@@ -31,7 +31,7 @@ public class UserController {
@GetMapping @GetMapping
public List<UserResponse> getAllUsers() { public List<UserResponse> getAllUsers() {
logger.info("Запрос на получение всех пользователей"); logger.info("Получен запрос на получение всех пользователей");
try { try {
List<User> users = userRepository.findAll(); List<User> users = userRepository.findAll();

View File

@@ -0,0 +1,50 @@
package com.magistr.app.dto;
public class CreateSubjectRequest {
private Long id;
private String name;
private String code;
private Long departmentId;
public CreateSubjectRequest() {};
public CreateSubjectRequest(Long id, String name, String code, Long departmentId) {
this.id = id;
this.name = name;
this.code = code;
this.departmentId = departmentId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
}

View File

@@ -0,0 +1,35 @@
package com.magistr.app.dto;
public class SubjectResponse {
private Long id;
private String name;
private String code;
private Long departmentId;
public SubjectResponse() {};
public SubjectResponse(Long id, String name, String code, Long departmentId) {
this.id = id;
this.name = name;
this.code = code;
this.departmentId = departmentId;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public Long getDepartmentId() {
return departmentId;
}
}

View File

@@ -13,12 +13,20 @@ public class Subject {
@Column(unique = true, nullable = false, length = 200) @Column(unique = true, nullable = false, length = 200)
private String name; private String name;
@Column(name = "code")
private String code;
@Column(name = "department_id", nullable = false)
private Long departmentId;
public Subject() { public Subject() {
} }
public Subject(Long id, String name) { public Subject(Long id, String name, String code, Long departmentId) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.code = code;
this.departmentId = departmentId;
} }
public Long getId() { public Long getId() {
@@ -36,4 +44,20 @@ public class Subject {
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
} }