- •Цель работы
- •Теоретическая часть
- •Слоистая архитектура
- •Ключевые понятия
- •Ход выполнения работы
- •Часть 0. Подготовка
- •Часть 1. Подключение Spring Data JPA и PostgreSQL
- •Часть 2. Создание сущностей и перечислений
- •2.1. Создайте перечисления NotificationChannel и NotificationStatus
- •2.2. Создайте сущность User
- •2.3. Создайте сущность Notification
- •Часть 3. Создание DTO и репозиториев
- •3.1. DTO для User
- •3.2. DTO для Notification
- •3.3. Создайте репозитории
- •Часть 4. Реализация CRUD для User
- •4.1. Создайте UserService
- •4.2. Создайте UserController
- •Часть 5. Реализация CRUD для Notification
- •5.1. Создайте NotificationService
- •5.2. Создайте NotificationController
- •5.3. Проверьте работу CRUD-операций для Notification
- •Часть 6. Методы репозитория Spring Data JPA
- •6.1. Запрос по нескольким параметрам
- •6.2. Сортировка в имени метода
- •6.3. Использование @Query
- •Часть 7. Транзакции
- •Часть 8. Проверка работы приложения в Postman
- •Часть 9. Валидация данных
- •Самостоятельные задания
- •Контрольные вопросы
•GET http://localhost:8080/users/all
•GET http://localhost:8080/users/{id}
•PUT http://localhost:8080/users/{id}
•DELETE http://localhost:8080/users/{id}
Пример JSON для создания пользователя:
{
"name": "Иван Иванов", "email": "ivan@example.com", "phone": "+79990001122",
"deviceToken": "device-token-123", "telegramChatId": "123456789"
}
Часть 5. Реализация CRUD для Notification
5.1. Создайте NotificationService
package org.example.service;
import lombok.RequiredArgsConstructor; import org.example.model.dto.NotificationDto; import org.example.model.entity.Notification; import org.example.model.entity.User;
import org.example.model.enums.NotificationChannel; import org.example.model.enums.NotificationStatus; import org.example.repository.NotificationRepository; import org.example.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime; import java.util.List;
@Service
@RequiredArgsConstructor
public class NotificationService {
private final NotificationRepository notificationRepository; private final UserRepository userRepository;
public Notification createNotification(NotificationDto request) { User user =
userRepository.findById(request.getRecipientId()).orElseThrow();
Notification notification = new Notification(); notification.setTitle(request.getTitle()); notification.setMessage(request.getMessage()); notification.setChannel(request.getChannel());
12
notification.setStatus(NotificationStatus.CREATED);
notification.setCreatedAt(LocalDateTime.now());
notification.setRecipient(user);
return notificationRepository.save(notification);
}
public List<Notification> getAllNotifications() { return notificationRepository.findAll();
}
public Notification getNotificationById(Long id) {
return notificationRepository.findById(id).orElseThrow();
}
public Notification updateNotification(Long id, NotificationDto request)
{
Notification notification = notificationRepository.findById(id).orElseThrow();
notification.setTitle(request.getTitle());
notification.setMessage(request.getMessage());
notification.setChannel(request.getChannel());
notification.setStatus(request.getStatus()); return notificationRepository.save(notification);
}
public void deleteNotification(Long id) { Notification notification =
notificationRepository.findById(id).orElseThrow(); notificationRepository.delete(notification);
}
public List<Notification> getNotificationsByStatus(NotificationStatus status) {
return notificationRepository.findByStatus(status);
}
public List<Notification> getNotificationsByChannel(NotificationChannel channel) {
return notificationRepository.findByChannel(channel);
}
public List<Notification> getNotificationsByRecipientId(Long recipientId) {
return notificationRepository.findByRecipientId(recipientId);
}
}
13
5.2. Создайте NotificationController
package org.example.controller;
import jakarta.validation.Valid; import lombok.RequiredArgsConstructor;
import org.example.model.dto.NotificationDto; import org.example.model.entity.Notification; import org.example.model.enums.NotificationChannel; import org.example.model.enums.NotificationStatus; import org.example.service.NotificationService; import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController @RequestMapping("/notifications") @RequiredArgsConstructor
public class NotificationController {
private final NotificationService notificationService;
@PostMapping("/add")
public NotificationDto createNotification(@RequestBody @Valid NotificationDto request) {
Notification response = notificationService.createNotification(request);
return NotificationDto.builder()
.title(response.getTitle())
.message(response.getMessage())
.channel(response.getChannel())
.status(response.getStatus())
.createdAt(response.getCreatedAt())
.sentAt(response.getSentAt())
.recipientId(response.getRecipient().getId())
.build();
}
@GetMapping("/all")
public List<NotificationDto> getAllNotifications() {
return notificationService.getAllNotifications().stream()
.map(response -> NotificationDto.builder()
.title(response.getTitle())
.message(response.getMessage())
.channel(response.getChannel())
.status(response.getStatus())
.createdAt(response.getCreatedAt())
.sentAt(response.getSentAt())
.recipientId(response.getRecipient().getId())
.build())
.toList();
14
}
@GetMapping("/{id}")
public NotificationDto getNotificationById(@PathVariable Long id) { Notification response = notificationService.getNotificationById(id); return NotificationDto.builder()
.title(response.getTitle())
.message(response.getMessage())
.channel(response.getChannel())
.status(response.getStatus())
.createdAt(response.getCreatedAt())
.sentAt(response.getSentAt())
.recipientId(response.getRecipient().getId())
.build();
}
@PutMapping("/{id}")
public NotificationDto updateNotification(@PathVariable Long id, @RequestBody @Valid
NotificationDto request) {
Notification response = notificationService.updateNotification(id, request);
return NotificationDto.builder()
.title(response.getTitle())
.message(response.getMessage())
.channel(response.getChannel())
.status(response.getStatus())
.createdAt(response.getCreatedAt())
.sentAt(response.getSentAt())
.recipientId(response.getRecipient().getId())
.build();
}
@DeleteMapping("/{id}")
public String deleteNotification(@PathVariable Long id) { notificationService.deleteNotification(id);
return "Уведомление удалено";
}
@GetMapping("/status/{status}")
public List<NotificationDto> getByStatus(@PathVariable NotificationStatus status) {
return notificationService.getNotificationsByStatus(status).stream()
.map(response -> NotificationDto.builder()
.title(response.getTitle())
.message(response.getMessage())
.channel(response.getChannel())
.status(response.getStatus())
.createdAt(response.getCreatedAt())
.sentAt(response.getSentAt())
.recipientId(response.getRecipient().getId())
15
