Compare commits
8 Commits
Author | SHA1 | Date | |
---|---|---|---|
baf5215626 | |||
5fbd7c5510 | |||
745795e7b7 | |||
1874d96ed7 | |||
e11781e6c1 | |||
3e9d61d071 | |||
6137e97499 | |||
6f0a431bd9 |
@ -7,6 +7,17 @@ plugins {
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
defaultTasks 'bootRun'
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
bootJar {
|
||||
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
|
||||
}
|
||||
|
||||
assert System.properties['java.specification.version'] == '17' || '21'
|
||||
java {
|
||||
sourceCompatibility = '17'
|
||||
}
|
||||
@ -17,6 +28,13 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
|
BIN
demo/data.mv.db
Normal file
BIN
demo/data.mv.db
Normal file
Binary file not shown.
@ -1,13 +1,102 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.service.MessageService;
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.orders.service.OrderService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
// Логгер
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
// Бизнес-логика для сущности "Тип" (Тип книг)
|
||||
private final TypeService typeService;
|
||||
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
private final OrderService orderService;
|
||||
|
||||
// Бизнес-логика для сущности "Пользователь"
|
||||
private final UserService userService;
|
||||
|
||||
// Бизнес-логика для сущности "Сообщение"
|
||||
private final MessageService messageService;
|
||||
|
||||
// Конструктор
|
||||
public DemoApplication(
|
||||
TypeService typeService,
|
||||
OrderService orderService,
|
||||
UserService userService,
|
||||
MessageService messageService) {
|
||||
this.typeService = typeService;
|
||||
this.orderService = orderService;
|
||||
this.userService = userService;
|
||||
this.messageService = messageService;
|
||||
}
|
||||
|
||||
// Входная точка программы
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
if (args.length > 0 && Objects.equals("--populate", args[0])) {
|
||||
log.info("Create default types values");
|
||||
final var type1 = typeService.create(new TypeEntity("Protection"));
|
||||
final var type2 = typeService.create(new TypeEntity("Sharpness"));
|
||||
final var type3 = typeService.create(new TypeEntity("Infinity"));
|
||||
|
||||
log.info("Create default users values");
|
||||
final var user1 = userService.create(new UserEntity("User1", "password", "mail1@gmail.com"));
|
||||
final var user2 = userService.create(new UserEntity("User2", "password", "mail2@gmail.com"));
|
||||
final var user3 = userService.create(new UserEntity("User3", "password", "mail3@gmail.com"));
|
||||
|
||||
log.info("Create default order values");
|
||||
final var orders = List.of(
|
||||
new OrderEntity(type1, 12.00, 3),
|
||||
new OrderEntity(type1, 50.00, 20),
|
||||
new OrderEntity(type2, 15.00, 30),
|
||||
new OrderEntity(type2, 64.00, 10),
|
||||
new OrderEntity(type2, 15.00, 6),
|
||||
new OrderEntity(type3, 80.00, 6),
|
||||
new OrderEntity(type3, 64.00, 3)
|
||||
);
|
||||
orders.forEach(order -> orderService.create(user1.getId(), order));
|
||||
|
||||
log.info("Create default messages values");
|
||||
final var messages1 = List.of(
|
||||
new MessageEntity("Message1", LocalDateTime.now(), false),
|
||||
new MessageEntity("Message2", LocalDateTime.now(), false),
|
||||
new MessageEntity("Message3", LocalDateTime.now(), false)
|
||||
);
|
||||
messages1.forEach(message -> messageService.create(user1.getId(), message));
|
||||
|
||||
final var messages2 = List.of(
|
||||
new MessageEntity("Message4", LocalDateTime.now(), false),
|
||||
new MessageEntity("Message5", LocalDateTime.now(), false)
|
||||
);
|
||||
messages2.forEach(message -> messageService.create(user2.getId(), message));
|
||||
|
||||
final var messages3 = List.of(
|
||||
new MessageEntity("Message6", LocalDateTime.now(), false),
|
||||
new MessageEntity("Message7", LocalDateTime.now(), false)
|
||||
);
|
||||
messages3.forEach(message -> messageService.create(user3.getId(), message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
117
demo/src/main/java/com/example/demo/core/api/PageDto.java
Normal file
117
demo/src/main/java/com/example/demo/core/api/PageDto.java
Normal file
@ -0,0 +1,117 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
// DTO для страниц (Пагинация)
|
||||
public class PageDto<D> {
|
||||
// Список элементов
|
||||
private List<D> items = new ArrayList<>();
|
||||
|
||||
// Количество элементов
|
||||
private int itemsCount;
|
||||
|
||||
// Текущая страница
|
||||
private int currentPage;
|
||||
|
||||
// Текущий размер
|
||||
private int currentSize;
|
||||
|
||||
// Общее количество страниц
|
||||
private int totalPages;
|
||||
|
||||
// Общее количество элементов
|
||||
private long totalItems;
|
||||
|
||||
// Первая страница
|
||||
private boolean isFirst;
|
||||
|
||||
// Последняя страница
|
||||
private boolean isLast;
|
||||
|
||||
// Есть следующая старница
|
||||
private boolean hasNext;
|
||||
|
||||
// Есть предыдущая страница
|
||||
private boolean hasPrevious;
|
||||
|
||||
public List<D> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<D> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public int getItemsCount() {
|
||||
return itemsCount;
|
||||
}
|
||||
|
||||
public void setItemsCount(int itemsCount) {
|
||||
this.itemsCount = itemsCount;
|
||||
}
|
||||
|
||||
public int getCurrentPage() {
|
||||
return currentPage;
|
||||
}
|
||||
|
||||
public void setCurrentPage(int currentPage) {
|
||||
this.currentPage = currentPage;
|
||||
}
|
||||
|
||||
public int getCurrentSize() {
|
||||
return currentSize;
|
||||
}
|
||||
|
||||
public void setCurrentSize(int currentSize) {
|
||||
this.currentSize = currentSize;
|
||||
}
|
||||
|
||||
public int getTotalPages() {
|
||||
return totalPages;
|
||||
}
|
||||
|
||||
public void setTotalPages(int totalPages) {
|
||||
this.totalPages = totalPages;
|
||||
}
|
||||
|
||||
public long getTotalItems() {
|
||||
return totalItems;
|
||||
}
|
||||
|
||||
public void setTotalItems(long totalItems) {
|
||||
this.totalItems = totalItems;
|
||||
}
|
||||
|
||||
public boolean isFirst() {
|
||||
return isFirst;
|
||||
}
|
||||
|
||||
public void setFirst(boolean isFirst) {
|
||||
this.isFirst = isFirst;
|
||||
}
|
||||
|
||||
public boolean isLast() {
|
||||
return isLast;
|
||||
}
|
||||
|
||||
public void setLast(boolean isLast) {
|
||||
this.isLast = isLast;
|
||||
}
|
||||
|
||||
public boolean isHasNext() {
|
||||
return hasNext;
|
||||
}
|
||||
|
||||
public void setHasNext(boolean hasNext) {
|
||||
this.hasNext = hasNext;
|
||||
}
|
||||
|
||||
public boolean isHasPrevious() {
|
||||
return hasPrevious;
|
||||
}
|
||||
|
||||
public void setHasPrevious(boolean hasPrevious) {
|
||||
this.hasPrevious = hasPrevious;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
// Преобразование в DTO страниц (Пагинация)
|
||||
public class PageDtoMapper {
|
||||
private PageDtoMapper() {
|
||||
}
|
||||
|
||||
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
|
||||
final PageDto<D> dto = new PageDto<>();
|
||||
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
|
||||
dto.setItemsCount(page.getNumberOfElements());
|
||||
dto.setCurrentPage(page.getNumber());
|
||||
dto.setCurrentSize(page.getSize());
|
||||
dto.setTotalPages(page.getTotalPages());
|
||||
dto.setTotalItems(page.getTotalElements());
|
||||
dto.setFirst(page.isFirst());
|
||||
dto.setLast(page.isLast());
|
||||
dto.setHasNext(page.hasNext());
|
||||
dto.setHasPrevious(page.hasPrevious());
|
||||
return dto;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
// Класс для задания констант
|
||||
public class Constants {
|
||||
// Имя последовательности
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
// Базовый префикс REST-API
|
||||
public static final String API_URL = "/api/1.0";
|
||||
|
||||
// Размер страницы пагинации
|
||||
public static final String DEFAULT_PAGE_SIZE = "5";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
// Конфигурация для библиотеки ModelMapper
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
// Конфигурация для отключения Cors-проверки
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
// Собственное непроверяемое исключение
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public <T> NotFoundException(Class<T> clazz, Long id) {
|
||||
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
// Абстрактный класс для базовой сущности
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
// Идентфикатор
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
|
||||
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
|
||||
protected Long id;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
// Получить идентификатор
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// Установить идентификатор
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
package com.example.demo.messages.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.service.MessageService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Сообщение"
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user/{user}/message")
|
||||
public class MessageController {
|
||||
// Бизнес-логика для сущности "Сообщение"
|
||||
private final MessageService messageService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public MessageController(MessageService messageService, ModelMapper modelMapper) {
|
||||
this.messageService = messageService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private MessageDto toDto(MessageEntity entity) {
|
||||
return modelMapper.map(entity, MessageDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private MessageEntity toEntity(@Valid MessageDto dto) {
|
||||
final MessageEntity entity = modelMapper.map(dto, MessageEntity.class);
|
||||
return entity;
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@GetMapping
|
||||
public PageDto<MessageDto> getAll(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(messageService.getAll(userId, page, size), this::toDto);
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@GetMapping("/{id}")
|
||||
public MessageDto get(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(messageService.get(userId, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@PostMapping
|
||||
public MessageDto create(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestBody @Valid MessageDto dto) {
|
||||
return toDto(messageService.create(userId, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public MessageDto update(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid MessageDto dto) {
|
||||
return toDto(messageService.update(userId, id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public MessageDto delete(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(messageService.delete(userId, id));
|
||||
}
|
||||
}
|
@ -0,0 +1,82 @@
|
||||
package com.example.demo.messages.api;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
// DTO для сущности "Сообщение"
|
||||
public class MessageDto {
|
||||
// Идентфикатор
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// Идентификатор отправителя сообщения
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long userId;
|
||||
|
||||
// Текст сообщения
|
||||
@NotBlank
|
||||
private String text;
|
||||
|
||||
// Дата отправки
|
||||
private LocalDateTime date;
|
||||
|
||||
// Признак публикации сообщения
|
||||
@JsonProperty(defaultValue = "false")
|
||||
private boolean isPublished;
|
||||
|
||||
// Получить идентификатор
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// Установить идентификатор
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
// Получить идентификатор отправителя сообщения
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
// Установить идентификатор отправителя сообщения
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
// Получить текст сообщения
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Установить текст сообщения
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
// Получить дату отправления
|
||||
public LocalDateTime getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
// Установить дату отправления
|
||||
public void setDate(LocalDateTime date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
// Получить признак публикации сообщения
|
||||
public boolean getIsPublished() {
|
||||
return isPublished;
|
||||
}
|
||||
|
||||
// Установить признак публикации сообщения
|
||||
public void setIsPublished(boolean isPublished) {
|
||||
this.isPublished = isPublished;
|
||||
}
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package com.example.demo.messages.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Column;
|
||||
|
||||
// Сущность "Сообщение"
|
||||
@Entity
|
||||
@Table(name = "messages")
|
||||
public class MessageEntity extends BaseEntity {
|
||||
// Отправитель сообщения
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
// Текст сообщения
|
||||
@Column(nullable = false)
|
||||
private String text;
|
||||
|
||||
// Дата отправки
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime date;
|
||||
|
||||
// Признак публикации сообщения
|
||||
@Column(nullable = false)
|
||||
private boolean isPublished;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public MessageEntity() {
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public MessageEntity(String text, LocalDateTime date, boolean isPublished) {
|
||||
this.text = text;
|
||||
this.date = date;
|
||||
this.isPublished = isPublished;
|
||||
}
|
||||
|
||||
// Получить отправителя
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
// Установить отправителя
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
if (!user.getMessages().contains(this)) {
|
||||
user.getMessages().add(this);
|
||||
}
|
||||
}
|
||||
|
||||
// Получить текст сообщения
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Установить текст сообщения
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
// Получить дату отправления
|
||||
public LocalDateTime getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
// Установить дату отправления
|
||||
public void setDate(LocalDateTime date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
// Получить признак публикации сообщения
|
||||
public boolean getIsPublished() {
|
||||
return isPublished;
|
||||
}
|
||||
|
||||
// Установить признак публикации сообщения
|
||||
public void setIsPublished(boolean isPublished) {
|
||||
this.isPublished = isPublished;
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user.getId(), text, date, isPublished);
|
||||
}
|
||||
|
||||
// Сравнить объекты
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final MessageEntity other = (MessageEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser().getId(), user.getId())
|
||||
&& Objects.equals(other.getText(), text)
|
||||
&& Objects.equals(other.getDate(), date)
|
||||
&& Objects.equals(other.getIsPublished(), isPublished);
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.messages.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
|
||||
// Хранилище для сущности "Сообщение"
|
||||
public interface MessageRepository extends CrudRepository<MessageEntity, Long>, PagingAndSortingRepository<MessageEntity, Long> {
|
||||
// Получить сообщение по пользователю и идентификатору
|
||||
Optional<MessageEntity> findOnyByUserIdAndId(Long userId, Long id);
|
||||
|
||||
// Получить список всех сообщений (с пагинацией)
|
||||
Page<MessageEntity> findAll(Pageable pageable);
|
||||
|
||||
// Получить список сообщений по пользователю
|
||||
List<MessageEntity> findByUserId(Long userId);
|
||||
|
||||
// Получить список сообщений по пользователю (с пагинацией)
|
||||
Page<MessageEntity> findByUserId(Long userId, Pageable pageable);
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
package com.example.demo.messages.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.repository.MessageRepository;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
// Бизнес-логика для сущности "Сообщение"
|
||||
@Service
|
||||
public class MessageService {
|
||||
// Хранилище элементов
|
||||
private final MessageRepository repository;
|
||||
|
||||
// Бизнес-логика для отправителей (пользователей)
|
||||
private final UserService userService;
|
||||
|
||||
// Конструктор
|
||||
public MessageService(MessageRepository repository, UserService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру
|
||||
@Transactional(readOnly = true)
|
||||
public List<MessageEntity> getAll(Long userId) {
|
||||
if (userId <= 0L) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
else {
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру (с пагинацией)
|
||||
@Transactional(readOnly = true)
|
||||
public Page<MessageEntity> getAll(Long userId, int page, int size) {
|
||||
final PageRequest pageRequest = PageRequest.of(page, size);
|
||||
if (userId <= 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
else {
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId, pageRequest);
|
||||
}
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@Transactional(readOnly = true)
|
||||
public MessageEntity get(Long userId, Long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOnyByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(MessageEntity.class, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@Transactional
|
||||
public MessageEntity create(Long userId, MessageEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
final UserEntity existsEntity = userService.get(userId);
|
||||
entity.setUser(existsEntity);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@Transactional
|
||||
public MessageEntity update(Long userId, Long id, MessageEntity entity) {
|
||||
userService.get(userId);
|
||||
final MessageEntity existsEntity = get(userId, id);
|
||||
existsEntity.setUser(entity.getUser());
|
||||
existsEntity.setText(entity.getText());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@Transactional
|
||||
public MessageEntity delete(Long userId, Long id) {
|
||||
userService.get(userId);
|
||||
final MessageEntity existsEntity = get(userId, id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
// Удалить все элементы
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,113 @@
|
||||
package com.example.demo.orders.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.orders.model.OrderGrouped;
|
||||
import com.example.demo.orders.service.OrderService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Заказ" (Заказ, содержащий книги)
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user/{user}/order")
|
||||
public class OrderController {
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
private final OrderService orderService;
|
||||
|
||||
// Бизнес-логика для сущности "Тип" (Тип книги)
|
||||
private final TypeService typeService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public OrderController(OrderService orderService, TypeService typeService, ModelMapper modelMapper) {
|
||||
this.orderService = orderService;
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private OrderDto toDto(OrderEntity entity) {
|
||||
return modelMapper.map(entity, OrderDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private OrderEntity toEntity(@Valid OrderDto dto) {
|
||||
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
|
||||
entity.setType(typeService.get(dto.getTypeId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
// Преобрзовать из сущности сгруппированных заказов в DTO
|
||||
private OrderGroupedDto toGroupedDto(OrderGrouped entity) {
|
||||
return modelMapper.map(entity, OrderGroupedDto.class);
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру
|
||||
@GetMapping
|
||||
public PageDto<OrderDto> getAll(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(orderService.getAll(userId, typeId, page, size), this::toDto);
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@GetMapping("/{id}")
|
||||
public OrderDto get(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(orderService.get(userId, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@PostMapping
|
||||
public OrderDto create(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestBody @Valid OrderDto dto) {
|
||||
return toDto(orderService.create(userId, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public OrderDto update(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid OrderDto dto) {
|
||||
return toDto(orderService.update(userId, id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public OrderDto delete(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(orderService.delete(userId, id));
|
||||
}
|
||||
|
||||
// Получить список заказов, сгруппированных по типу
|
||||
@GetMapping("/total")
|
||||
public List<OrderGroupedDto> getMethodName(@PathVariable(name = "user") Long userId) {
|
||||
return orderService.getTotal(userId).stream()
|
||||
.map(this::toGroupedDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
74
demo/src/main/java/com/example/demo/orders/api/OrderDto.java
Normal file
74
demo/src/main/java/com/example/demo/orders/api/OrderDto.java
Normal file
@ -0,0 +1,74 @@
|
||||
package com.example.demo.orders.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
// DTO для сущности "Заказ" (Заказ, содержащий книги)
|
||||
public class OrderDto {
|
||||
// Идентфикатор
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// Идентификатор типа книги
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long typeId;
|
||||
|
||||
// Цена книги
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Double price;
|
||||
|
||||
// Количество книг
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer count;
|
||||
|
||||
// Получить идентификатор
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// Установить идентификатор
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
// Получить идентификатор типа книги
|
||||
public Long getTypeId() {
|
||||
return typeId;
|
||||
}
|
||||
|
||||
// Установить идентификатор типа книги
|
||||
public void setTypeId(Long typeId) {
|
||||
this.typeId = typeId;
|
||||
}
|
||||
|
||||
// Получить цену книги
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
// Установить цену книги
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
// Получить количество книг
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
// Установить количество книг
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
// Получить сумму заказа
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Double getSum() {
|
||||
return price * count;
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.example.demo.orders.api;
|
||||
|
||||
// DTO для заказов, сгруппированных по типу
|
||||
public class OrderGroupedDto {
|
||||
// Идентификатор типа
|
||||
private Long typeId;
|
||||
|
||||
// Общая стоимость заказов
|
||||
private Long totalPrice;
|
||||
|
||||
// Общее количество заказов
|
||||
private Integer totalCount;
|
||||
|
||||
// Получить идентификатор типа
|
||||
public Long getTypeId() {
|
||||
return typeId;
|
||||
}
|
||||
|
||||
// Установить идентификатор типа
|
||||
public void setTypeId(Long typeId) {
|
||||
this.typeId = typeId;
|
||||
}
|
||||
|
||||
// Получить общую стоимость заказов
|
||||
public Long getTotalPrice() {
|
||||
return totalPrice;
|
||||
}
|
||||
|
||||
// Установить общую стоимость заказов
|
||||
public void setTotalPrice(Long totalPrice) {
|
||||
this.totalPrice = totalPrice;
|
||||
}
|
||||
|
||||
// Получить общее количество заказов
|
||||
public Integer getTotalCount() {
|
||||
return totalCount;
|
||||
}
|
||||
|
||||
// Установить общее количество заказов
|
||||
public void setTotalCount(Integer totalCount) {
|
||||
this.totalCount = totalCount;
|
||||
}
|
||||
}
|
@ -0,0 +1,111 @@
|
||||
package com.example.demo.orders.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
// Сущность "Заказ" (Заказ, содержащий книги)
|
||||
@Entity
|
||||
@Table(name = "orders")
|
||||
public class OrderEntity extends BaseEntity {
|
||||
// Тип книги
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "typeId", nullable = false)
|
||||
private TypeEntity type;
|
||||
|
||||
// Заказчик (пользователь)
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
// Цена книги
|
||||
@Column(nullable = false)
|
||||
private Double price;
|
||||
|
||||
// Количество книг
|
||||
@Column(nullable = false)
|
||||
private Integer count;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public OrderEntity() {
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public OrderEntity(TypeEntity type, Double price, Integer count) {
|
||||
this.type = type;
|
||||
this.price = price;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
// Получить тип книги
|
||||
public TypeEntity getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
// Установить тип книги
|
||||
public void setType(TypeEntity type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
// Получить заказчика (пользователя)
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
// Установить заказчика (пользователя)
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
if (!user.getOrders().contains(this)) {
|
||||
user.getOrders().add(this);
|
||||
}
|
||||
}
|
||||
|
||||
// Получить стоимость книги
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
// Установить стоимость книги
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
// Получить количество книг
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
// Установить количество книг
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, type, user.getId(), price, count);
|
||||
}
|
||||
|
||||
// Сравнить объекты
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final OrderEntity other = (OrderEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getType(), type)
|
||||
&& Objects.equals(other.getUser().getId(), user.getId())
|
||||
&& Objects.equals(other.getPrice(), price)
|
||||
&& Objects.equals(other.getCount(), count);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.orders.model;
|
||||
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
// Заказы, сгруппированные по типу
|
||||
public interface OrderGrouped {
|
||||
// Тип заказов
|
||||
TypeEntity getType();
|
||||
|
||||
// Общая сумма заказов
|
||||
double getTotalPrice();
|
||||
|
||||
// Общее количество заказов
|
||||
int getTotalCount();
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.example.demo.orders.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.orders.model.OrderGrouped;
|
||||
|
||||
// Хранилище для сущности "Заказ" (Заказ, содержащий книги)
|
||||
public interface OrderRepository extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
|
||||
// Получить заказ по пользователю и идентификатору
|
||||
Optional<OrderEntity> findOneByUserIdAndId(Long userId, Long id);
|
||||
|
||||
// Получить список заказов по пользователю
|
||||
List<OrderEntity> findByUserId(Long userId);
|
||||
|
||||
// Получить список заказов по пользователю (с пагинацией)
|
||||
Page<OrderEntity> findByUserId(Long userId, Pageable pageable);
|
||||
|
||||
// Получить список заказов по типу
|
||||
List<OrderEntity> findByUserIdAndTypeId(Long userId, Long typeId);
|
||||
|
||||
// Получить список заказов по типу (с пагинацией)
|
||||
Page<OrderEntity> findByUserIdAndTypeId(Long userId, Long typeId, Pageable pageable);
|
||||
|
||||
// Получить заказы, сгруппированные по типу
|
||||
// select
|
||||
// type.name,
|
||||
// coalesce(sum(order.price), 0),
|
||||
// coalesce(sum(order.count), 0)
|
||||
// from types as type
|
||||
// left join orders as order on type.id = order.type_id and order.user_id = ?
|
||||
// group by type.name order by type.id
|
||||
@Query("select "
|
||||
+ "t as type, "
|
||||
+ "coalesce(sum(o.price), 0) as totalPrice, "
|
||||
+ "coalesce(sum(o.count), 0) as totalCount "
|
||||
+ "from TypeEntity t left join OrderEntity o on o.type = t and o.user.id = ?1 "
|
||||
+ "group by t order by t.id")
|
||||
List<OrderGrouped> getOrdersTotalByType(long userId);
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.example.demo.orders.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.orders.model.OrderGrouped;
|
||||
import com.example.demo.orders.repository.OrderRepository;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
@Service
|
||||
public class OrderService {
|
||||
// Хранилище элементов
|
||||
private final OrderRepository repository;
|
||||
|
||||
// Бизнес-логика для заказчиков (пользователей)
|
||||
private final UserService userService;
|
||||
|
||||
// Конструктор
|
||||
public OrderService(OrderRepository repository, UserService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру
|
||||
@Transactional(readOnly = true)
|
||||
public List<OrderEntity> getAll(Long userId, Long typeId) {
|
||||
userService.get(userId);
|
||||
if (typeId <= 0L) {
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
else {
|
||||
return repository.findByUserIdAndTypeId(userId, typeId);
|
||||
}
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру (с пагинацией)
|
||||
@Transactional(readOnly = true)
|
||||
public Page<OrderEntity> getAll(long userId, long typeId, int page, int size) {
|
||||
final PageRequest pageRequest = PageRequest.of(page, size);
|
||||
userService.get(userId);
|
||||
if (typeId <= 0L) {
|
||||
return repository.findByUserId(userId, pageRequest);
|
||||
}
|
||||
return repository.findByUserIdAndTypeId(userId, typeId, pageRequest);
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@Transactional(readOnly = true)
|
||||
public OrderEntity get(Long userId, Long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(OrderEntity.class, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@Transactional
|
||||
public OrderEntity create(Long userId, OrderEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
final UserEntity existsUser = userService.get(userId);
|
||||
entity.setUser(existsUser);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@Transactional
|
||||
public OrderEntity update(Long userId, Long id, OrderEntity entity) {
|
||||
userService.get(userId);
|
||||
final OrderEntity existsEntity = get(userId, id);
|
||||
existsEntity.setType(entity.getType());
|
||||
existsEntity.setPrice(entity.getPrice());
|
||||
existsEntity.setCount(entity.getCount());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@Transactional
|
||||
public OrderEntity delete(Long userId, Long id) {
|
||||
userService.get(userId);
|
||||
final OrderEntity existsEntity = get(userId, id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
// Удалить все элементы
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
// Получить список заказов, сгруппированных по типу
|
||||
@Transactional(readOnly = true)
|
||||
public List<OrderGrouped> getTotal(long userId) {
|
||||
userService.get(userId);
|
||||
return repository.getOrdersTotalByType(userId);
|
||||
}
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Тип" (Тип книги)
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/type")
|
||||
public class TypeController {
|
||||
// Бизнес-логика для сущности "Тип" (Тип книги)
|
||||
private final TypeService typeService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public TypeController(TypeService typeService, ModelMapper modelMapper) {
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private TypeDto toDto(TypeEntity entity) {
|
||||
return modelMapper.map(entity, TypeDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private TypeEntity toEntity(@Valid TypeDto dto) {
|
||||
return modelMapper.map(dto, TypeEntity.class);
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@GetMapping
|
||||
public List<TypeDto> getAll() {
|
||||
return typeService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@GetMapping("/{id}")
|
||||
public TypeDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.get(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@PostMapping
|
||||
public TypeDto create(@RequestBody @Valid TypeDto dto) {
|
||||
return toDto(typeService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public TypeDto update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid TypeDto dto) {
|
||||
return toDto(typeService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public TypeDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.delete(id));
|
||||
}
|
||||
}
|
38
demo/src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
38
demo/src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
@ -0,0 +1,38 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
// DTO для сущности "Тип" (Тип книги)
|
||||
public class TypeDto {
|
||||
// Идентфикатор
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// Название типа
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
// Получить идентификатор
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.example.demo.types.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Column;
|
||||
|
||||
// Сущность "Тип" (Тип книги)
|
||||
@Entity
|
||||
@Table(name = "types")
|
||||
public class TypeEntity extends BaseEntity {
|
||||
// Название типа
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public TypeEntity() {
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public TypeEntity(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Получить название типа
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
// Установить название типа
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
|
||||
// Сравнить объекты
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final TypeEntity other = (TypeEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.types.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
// Хранилище для сущности "Тип" (Тип книги)
|
||||
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
|
||||
// Найти тип по названию (без учета регистра)
|
||||
Optional<TypeEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package com.example.demo.types.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.repository.TypeRepository;
|
||||
|
||||
// Бизнес-логика для сущности "Тип" (Тип книг)
|
||||
@Service
|
||||
public class TypeService {
|
||||
// Хранилище элементов
|
||||
private final TypeRepository repository;
|
||||
|
||||
// Конструктор
|
||||
public TypeService(TypeRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
// Проверка уникальности названия типа
|
||||
private void checkName(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Type with name %s is already exists", name));
|
||||
}
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@Transactional(readOnly = true)
|
||||
public List<TypeEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@Transactional(readOnly = true)
|
||||
public TypeEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(TypeEntity.class, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@Transactional
|
||||
public TypeEntity create(TypeEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkName(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@Transactional
|
||||
public TypeEntity update(Long id, TypeEntity entity) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
checkName(entity.getName());
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@Transactional
|
||||
public TypeEntity delete(Long id) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
// Удалить все элементы
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Пользователь"
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user")
|
||||
public class UserController {
|
||||
// Бизнес-логика для сущности "Пользователь"
|
||||
private final UserService userService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private UserEntity toEntity(@Valid UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@GetMapping
|
||||
public PageDto<UserDto> getAll(
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@GetMapping("/{id}")
|
||||
public UserDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.get(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@PostMapping
|
||||
public UserDto create(@RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public UserDto update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public UserDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.delete(id));
|
||||
}
|
||||
}
|
67
demo/src/main/java/com/example/demo/users/api/UserDto.java
Normal file
67
demo/src/main/java/com/example/demo/users/api/UserDto.java
Normal file
@ -0,0 +1,67 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
// DTO для сущности "Пользователь"
|
||||
public class UserDto {
|
||||
// Идентфикатор
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// Имя/логин пользователя
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 50)
|
||||
private String username;
|
||||
|
||||
// Пароль пользователя
|
||||
@NotBlank
|
||||
@Size(min = 8)
|
||||
private String password;
|
||||
|
||||
// Электронный адрес почты пользователя
|
||||
@NotBlank
|
||||
private String email;
|
||||
|
||||
// Получить идентификатор
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// Установить идентификатор
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
// Получить имя/логин пользователя
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
// Установить имя/логин пользователя
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
// Получить пароль пользователя
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
// Установить пароль пользователя
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
// Получить электронный адрес почты пользователя
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
// Установить электронный адрес почты пользователя
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
}
|
132
demo/src/main/java/com/example/demo/users/model/UserEntity.java
Normal file
132
demo/src/main/java/com/example/demo/users/model/UserEntity.java
Normal file
@ -0,0 +1,132 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.HashSet;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.OrderBy;
|
||||
|
||||
// Сущность "Пользователь"
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity extends BaseEntity {
|
||||
// Имя/логин пользователя
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String username;
|
||||
|
||||
// Пароль пользователя
|
||||
@Column(nullable = false, length = 50)
|
||||
private String password;
|
||||
|
||||
// Электронный адрес почты пользователя
|
||||
@Column(nullable = false, unique = true)
|
||||
private String email;
|
||||
|
||||
// Список заказов пользователя
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<OrderEntity> orders = new HashSet<>();
|
||||
|
||||
// Список сообщений пользователя
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<MessageEntity> messages = new HashSet<>();
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public UserEntity() {
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public UserEntity(String username, String password, String email) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
// Получить имя/логин пользователя
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
// Установить имя/логин пользователя
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
// Получить пароль пользователя
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
// Установить пароль пользователя
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
// Получить электронный адрес почты пользователя
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
// Установить электронный адрес почты пользователя
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
// Получить список заказов
|
||||
public Set<OrderEntity> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
// Добавить заказ
|
||||
public void addOrder(OrderEntity order) {
|
||||
if (order.getUser() != this) {
|
||||
order.setUser(this);
|
||||
}
|
||||
orders.add(order);
|
||||
}
|
||||
|
||||
// Получить список сообщений
|
||||
public Set<MessageEntity> getMessages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
// Добавить сообщение
|
||||
public void addMessage(MessageEntity message) {
|
||||
if (message.getUser() != this) {
|
||||
message.setUser(this);
|
||||
}
|
||||
messages.add(message);
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, username, password, email, orders, messages);
|
||||
}
|
||||
|
||||
// Сравнить объекты
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final UserEntity other = (UserEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUsername(), username)
|
||||
&& Objects.equals(other.getPassword(), password)
|
||||
&& Objects.equals(other.getEmail(), email)
|
||||
&& Objects.equals(other.getOrders(), orders)
|
||||
&& Objects.equals(other.getMessages(), messages);
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
// Хранилище для сущности "Пользователь"
|
||||
public interface UserRepository extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
|
||||
// Получить список всех пользовалей (с пагинацией)
|
||||
Page<UserEntity> findAll(Pageable pageable);
|
||||
|
||||
// Получить пользователя по имени/логину
|
||||
Optional<UserEntity> findByUsername(String username);
|
||||
|
||||
// Получить пользователя по адресу электронной почты
|
||||
Optional<UserEntity> findByEmail(String email);
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.example.demo.users.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.repository.UserRepository;
|
||||
|
||||
// Бизнес-логика для сущности "Пользователь"
|
||||
@Service
|
||||
public class UserService {
|
||||
// Хранилище элементов
|
||||
private final UserRepository repository;
|
||||
|
||||
// Конструктор
|
||||
public UserService(UserRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
// Проверка уникальности имени/логина пользователя
|
||||
private void checkUsername(String username) {
|
||||
if (repository.findByUsername(username).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with username %s is already exists", username));
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка уникальности адреса электронной почты пользователя
|
||||
private void checkEmail(String email) {
|
||||
if (repository.findByEmail(email).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with email %s is already exists", email));
|
||||
}
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
// Получить все элементы (с пагинацией)
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UserEntity> getAll(int page, int size) {
|
||||
final PageRequest pageRequest = PageRequest.of(page, size);
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@Transactional(readOnly = true)
|
||||
public UserEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@Transactional
|
||||
public UserEntity create(UserEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkUsername(entity.getUsername());
|
||||
checkEmail(entity.getEmail());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@Transactional
|
||||
public UserEntity update(Long id, UserEntity entity) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
existsEntity.setUsername(entity.getUsername());
|
||||
existsEntity.setPassword(entity.getPassword());
|
||||
existsEntity.setEmail(entity.getEmail());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@Transactional
|
||||
public UserEntity delete(Long id) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
// Удалить все элементы
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
@ -1 +1,20 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
server.port=8080
|
||||
|
||||
# Logger settings
|
||||
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA Settings
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.username=factorino
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
||||
# spring.jpa.show-sql=true
|
||||
# spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
# H2 console
|
||||
spring.h2.console.enabled=true
|
@ -1,13 +0,0 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class DemoApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
82
demo/src/test/java/com/example/demo/TypeServiceTests.java
Normal file
82
demo/src/test/java/com/example/demo/TypeServiceTests.java
Normal file
@ -0,0 +1,82 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class TypeServiceTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
private TypeEntity type;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
type = typeService.create(new TypeEntity("Protection"));
|
||||
typeService.create(new TypeEntity("Sharpness"));
|
||||
typeService.create(new TypeEntity("Infinity"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
typeService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertEquals(type, typeService.get(type.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final TypeEntity nonUniqueType = new TypeEntity("Protection");
|
||||
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final TypeEntity nullableType = new TypeEntity(null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final String oldName = type.getName();
|
||||
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
typeService.delete(type.getId());
|
||||
Assertions.assertEquals(2, typeService.getAll().size());
|
||||
|
||||
final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName()));
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertNotEquals(type.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.service.MessageService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UserMessageServiceTests {
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private MessageService messageService;
|
||||
|
||||
|
||||
private UserEntity user1;
|
||||
private UserEntity user2;
|
||||
private UserEntity user3;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
user1 = userService.create(new UserEntity("user1", "password", "mail1@gmail.com"));
|
||||
user2 = userService.create(new UserEntity("user2", "password", "mail2@gmail.com"));
|
||||
user3 = userService.create(new UserEntity("user3", "password", "mail3@gmail.com"));
|
||||
|
||||
final var messages1 = List.of(
|
||||
new MessageEntity("message1", LocalDateTime.now(), false),
|
||||
new MessageEntity("message2", LocalDateTime.now(), false),
|
||||
new MessageEntity("message3", LocalDateTime.now(), false)
|
||||
);
|
||||
messages1.forEach(message -> messageService.create(user1.getId(), message));
|
||||
|
||||
final var messages2 = List.of(
|
||||
new MessageEntity("Message4", LocalDateTime.now(), false),
|
||||
new MessageEntity("Message5", LocalDateTime.now(), false)
|
||||
);
|
||||
messages2.forEach(message -> messageService.create(user2.getId(), message));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
userService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
Assertions.assertEquals(5, messageService.getAll(0L).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void orderFilterTest() {
|
||||
Assertions.assertEquals(3, messageService.getAll(user1.getId()).size());
|
||||
Assertions.assertEquals(2, messageService.getAll(user2.getId()).size());
|
||||
Assertions.assertEquals(0, messageService.getAll(user3.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void userCascadeDeleteTest() {
|
||||
userService.delete(user1.getId());
|
||||
final var messages = entityManager.createQuery(
|
||||
"select count(o) from MessageEntity o where o.user.id = :userId");
|
||||
messages.setParameter("userId", user1.getId());
|
||||
Assertions.assertEquals(0, messages.getFirstResult());
|
||||
}
|
||||
}
|
100
demo/src/test/java/com/example/demo/UserOrderServiceTests.java
Normal file
100
demo/src/test/java/com/example/demo/UserOrderServiceTests.java
Normal file
@ -0,0 +1,100 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.orders.model.OrderEntity;
|
||||
import com.example.demo.orders.service.OrderService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UserOrderServiceTests {
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private OrderService orderService;
|
||||
|
||||
private TypeEntity type1;
|
||||
private TypeEntity type2;
|
||||
private TypeEntity type3;
|
||||
|
||||
private UserEntity user1;
|
||||
private UserEntity user2;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
type1 = typeService.create(new TypeEntity("Protection"));
|
||||
type2 = typeService.create(new TypeEntity("Sharpness"));
|
||||
type3 = typeService.create(new TypeEntity("Infinity"));
|
||||
|
||||
user1 = userService.create(new UserEntity("user1", "password", "mail1@gmail.com"));
|
||||
user2 = userService.create(new UserEntity("user2", "password", "mail2@gmail.com"));
|
||||
|
||||
final var orders = List.of(
|
||||
new OrderEntity(type1, 12.00, 3),
|
||||
new OrderEntity(type1, 50.00, 20),
|
||||
new OrderEntity(type2, 15.00, 30),
|
||||
new OrderEntity(type2, 64.00, 10),
|
||||
new OrderEntity(type2, 15.00, 6),
|
||||
new OrderEntity(type3, 80.00, 6),
|
||||
new OrderEntity(type3, 64.00, 3)
|
||||
);
|
||||
orders.forEach(order -> orderService.create(user1.getId(), order));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
userService.deleteAll();
|
||||
typeService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
Assertions.assertEquals(7, orderService.getAll(user1.getId(), 0L).size());
|
||||
Assertions.assertEquals(0, orderService.getAll(user2.getId(), 0L).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void orderFilterTest() {
|
||||
Assertions.assertEquals(2, orderService.getAll(user1.getId(), type1.getId()).size());
|
||||
Assertions.assertEquals(3, orderService.getAll(user1.getId(), type2.getId()).size());
|
||||
Assertions.assertEquals(2, orderService.getAll(user1.getId(), type3.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void userCascadeDeleteTest() {
|
||||
userService.delete(user1.getId());
|
||||
final var orders = entityManager.createQuery(
|
||||
"select count(o) from OrderEntity o where o.user.id = :userId");
|
||||
orders.setParameter("userId", user1.getId());
|
||||
Assertions.assertEquals(0, orders.getFirstResult());
|
||||
}
|
||||
}
|
14
demo/src/test/resources/application.properties
Normal file
14
demo/src/test/resources/application.properties
Normal file
@ -0,0 +1,14 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
|
||||
# Logger settings
|
||||
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA Settings
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.username=factorino
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
Loading…
x
Reference in New Issue
Block a user