Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
6628408c30 | |||
566bb17f71 | |||
2313a080a7 | |||
|
79bbcca648 | ||
|
7526d3fd8b | ||
|
b6afa8355f | ||
|
33a16a76ae | ||
|
cd388cff5c | ||
|
6b9a2025ed | ||
7369280716 | |||
|
b9859be707 | ||
|
2d53d7dc86 | ||
|
431abe9c99 | ||
|
f087bc5e96 | ||
|
e364145f5e | ||
|
e79da32126 | ||
e92ced5360 | |||
9442307ff8 | |||
|
5775804908 |
18
build.gradle
18
build.gradle
@ -1,12 +1,23 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.4'
|
||||
id 'org.springframework.boot' version '3.2.5'
|
||||
id 'io.spring.dependency-management' version '1.1.4'
|
||||
}
|
||||
|
||||
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,7 +28,12 @@ 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
data.mv.db
Normal file
BIN
data.mv.db
Normal file
Binary file not shown.
1792
data.trace.db
Normal file
1792
data.trace.db
Normal file
File diff suppressed because it is too large
Load Diff
18
gradle/wrapper/gradle-wrapper.properties
vendored
18
gradle/wrapper/gradle-wrapper.properties
vendored
@ -1,6 +1,22 @@
|
||||
#
|
||||
# Copyright 2012-2024 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
61
index.html
61
index.html
@ -1,61 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
<p id="out">Push the button</p>
|
||||
<input id="name"/>
|
||||
<br/>
|
||||
<button onclick="get()">Get</button>
|
||||
<br/>
|
||||
<button onclick="getTest()">Get Test</button>
|
||||
<br/>
|
||||
<button onclick="post()">Post</button>
|
||||
<br/>
|
||||
<button onclick="put()">Put</button>
|
||||
</body>
|
||||
<script>
|
||||
const url = "http://localhost:8080/api";
|
||||
const out = document.getElementById("out");
|
||||
const name = document.getElementById("name");
|
||||
const get = async () => {
|
||||
const res = await fetch(`${url}?name=${name.value}`);
|
||||
const text = await res.text();
|
||||
out.innerText = text;
|
||||
}
|
||||
const getTest = async () => {
|
||||
const res = await fetch(`${url}/test`);
|
||||
const text = await res.text();
|
||||
out.innerText = text;
|
||||
}
|
||||
const post = async () => {
|
||||
if (!name.value) {
|
||||
alert("Name is required");
|
||||
return;
|
||||
}
|
||||
const res = await fetch(url, {
|
||||
method: 'post',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: name.value
|
||||
});
|
||||
const text = await res.text();
|
||||
out.innerText = text;
|
||||
}
|
||||
const put = async () => {
|
||||
if (!name.value) {
|
||||
alert("Name is required");
|
||||
return;
|
||||
}
|
||||
const res = await fetch(`${url}/${name.value}`, {
|
||||
method: 'put',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: name.value
|
||||
});
|
||||
const text = await res.text();
|
||||
out.innerText = text;
|
||||
}
|
||||
</script>
|
||||
</html>
|
@ -1,49 +0,0 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class ApiController {
|
||||
List<UserInfo> objects = new ArrayList<>();
|
||||
|
||||
@GetMapping
|
||||
public List<UserInfo> getAll() {
|
||||
return objects;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UserInfo getId(@PathVariable(name = "id") int id) {
|
||||
return objects.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UserInfo create(@RequestBody UserInfo UserInfo) {
|
||||
objects.add(UserInfo);
|
||||
return UserInfo;
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserInfo update(@PathVariable(name = "id") int id, @RequestBody UserInfo entity) {
|
||||
objects.get(id);
|
||||
objects.add(id, entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UserInfo delete(@PathVariable(name = "id") int id) {
|
||||
var data = objects.get(id);
|
||||
objects.remove(id);
|
||||
return data;
|
||||
}
|
||||
}
|
@ -1,12 +1,70 @@
|
||||
package com.example.demo;
|
||||
|
||||
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;
|
||||
|
||||
import com.example.demo.categories.model.CategoriesEntity;
|
||||
import com.example.demo.categories.service.CategoriesService;
|
||||
import com.example.demo.orders.model.OrdersEntity;
|
||||
import com.example.demo.orders.service.OrdersService;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.products.service.ProductsService;
|
||||
import com.example.demo.users.model.UsersEntity;
|
||||
import com.example.demo.users.service.UsersService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final UsersService userService;
|
||||
private final CategoriesService categoriesService;
|
||||
private final ProductsService productsService;
|
||||
private final OrdersService ordersService;
|
||||
|
||||
public DemoApplication(CategoriesService categoriesService, ProductsService productsService,
|
||||
UsersService userService, OrdersService ordersService) {
|
||||
|
||||
this.userService = userService;
|
||||
this.categoriesService = categoriesService;
|
||||
this.productsService = productsService;
|
||||
this.ordersService = ordersService;
|
||||
}
|
||||
|
||||
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("Создание пользователей");
|
||||
final var user1 = userService.create(new UsersEntity("Natalia", "1234"));
|
||||
userService.create(new UsersEntity("Revengel", "4567"));
|
||||
|
||||
log.info("Создание категорий");
|
||||
final var category1 = categoriesService.create(new CategoriesEntity("Ноутбуки"));
|
||||
final var category2 = categoriesService.create(new CategoriesEntity("Телефоны"));
|
||||
|
||||
log.info("Создание продуктов");
|
||||
final var product1 = productsService.create(new ProductsEntity(category1, "Lenovo IDEA PAD 13", 15232.00));
|
||||
final var product2 = productsService.create(new ProductsEntity(category1, "Acer", 20300.00));
|
||||
final var product3 = productsService.create(new ProductsEntity(category2, "Iphone 13", 150000.00));
|
||||
|
||||
log.info("Создание заказов");
|
||||
|
||||
final var orders = List.of(
|
||||
new OrdersEntity(product1, 3, "03.04.2024"),
|
||||
new OrdersEntity(product2, 2, "02.04.2024"),
|
||||
new OrdersEntity(product3, 1, "05.04.2024"),
|
||||
new OrdersEntity(product1, 4, "03.04.2024"));
|
||||
orders.forEach(order -> ordersService.create(user1.getId(), order));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,51 +0,0 @@
|
||||
package com.example.demo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class UserInfo {
|
||||
private String login;
|
||||
private String password;
|
||||
private String email;
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public UserInfo() {
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public UserInfo(
|
||||
@JsonProperty(value = "login") String login,
|
||||
@JsonProperty(value = "password") String password,
|
||||
@JsonProperty(value = "email") String email,
|
||||
@JsonProperty(value = "name") String name,
|
||||
@JsonProperty(value = "age") Integer age) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.email = email;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.categories.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.categories.model.CategoriesEntity;
|
||||
import com.example.demo.categories.service.CategoriesService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/Categories")
|
||||
public class CategoriesController {
|
||||
private final CategoriesService categoriesService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public CategoriesController(CategoriesService categoriesService, ModelMapper modelMapper) {
|
||||
this.categoriesService = categoriesService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private CategoriesDto toDto(CategoriesEntity entity) {
|
||||
return modelMapper.map(entity, CategoriesDto.class);
|
||||
}
|
||||
|
||||
private CategoriesEntity toEntity(CategoriesDto dto) {
|
||||
return modelMapper.map(dto, CategoriesEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CategoriesDto> getAll() {
|
||||
return categoriesService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CategoriesDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(categoriesService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CategoriesDto create(@RequestBody @Valid CategoriesDto dto) {
|
||||
return toDto(categoriesService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CategoriesDto update(@PathVariable(name = "id") Long id, @RequestBody CategoriesDto dto) {
|
||||
return toDto(categoriesService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CategoriesDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(categoriesService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.categories.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class CategoriesDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
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,47 @@
|
||||
package com.example.demo.categories.model;
|
||||
|
||||
import java.util.Objects;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "categories")
|
||||
public class CategoriesEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
|
||||
public CategoriesEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CategoriesEntity(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 CategoriesEntity other = (CategoriesEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.example.demo.categories.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.categories.model.CategoriesEntity;
|
||||
|
||||
public interface CategoriesRepository extends CrudRepository<CategoriesEntity, Long> {
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.example.demo.categories.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.categories.model.CategoriesEntity;
|
||||
import com.example.demo.categories.repository.CategoriesRepository;
|
||||
|
||||
@Service
|
||||
public class CategoriesService {
|
||||
private final CategoriesRepository repository;
|
||||
|
||||
public CategoriesService(CategoriesRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CategoriesEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public CategoriesEntity get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new NotFoundException(CategoriesEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CategoriesEntity create(CategoriesEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CategoriesEntity update(Long id, CategoriesEntity entity) {
|
||||
final CategoriesEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CategoriesEntity delete(Long id) {
|
||||
final CategoriesEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
97
src/main/java/com/example/demo/core/api/PageDto.java
Normal file
97
src/main/java/com/example/demo/core/api/PageDto.java
Normal file
@ -0,0 +1,97 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
25
src/main/java/com/example/demo/core/api/PageDtoMapper.java
Normal file
25
src/main/java/com/example/demo/core/api/PageDtoMapper.java
Normal file
@ -0,0 +1,25 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
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,12 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
public static final String API_URL = "/api/1.0";
|
||||
|
||||
public static final String DEFAULT_PAGE_SIZE = "5";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.example.demo;
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
@ -6,7 +6,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
@ -0,0 +1,7 @@
|
||||
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));
|
||||
}
|
||||
}
|
32
src/main/java/com/example/demo/core/model/BaseEntity.java
Normal file
32
src/main/java/com/example/demo/core/model/BaseEntity.java
Normal file
@ -0,0 +1,32 @@
|
||||
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() {
|
||||
}
|
||||
|
||||
protected BaseEntity(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package com.example.demo.orders.api;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
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.configuration.Constants;
|
||||
import com.example.demo.orders.model.OrdersEntity;
|
||||
import com.example.demo.orders.service.OrdersService;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.products.service.ProductsService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user/{user}/order")
|
||||
public class OrdersController {
|
||||
private final OrdersService ordersService;
|
||||
private final ProductsService productsService;
|
||||
private final ModelMapper modelMapper;
|
||||
private SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy");
|
||||
|
||||
public OrdersController(OrdersService ordersService, ProductsService productsService, ModelMapper modelMapper) {
|
||||
this.ordersService = ordersService;
|
||||
this.productsService = productsService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
public Date StringConvertDate(String date) {
|
||||
|
||||
try {
|
||||
return formater.parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String DateConvertString(Date date) {
|
||||
return formater.format(date);
|
||||
}
|
||||
|
||||
private OrdersDto toDto(OrdersEntity entity) {
|
||||
// String dateEntity = DateConvertString(entity.getDate());
|
||||
// entity.setDate(dateEntity);
|
||||
return modelMapper.map(entity, OrdersDto.class);
|
||||
}
|
||||
|
||||
private OrdersEntity toEntity(OrdersDto dto) {
|
||||
final OrdersEntity entity = modelMapper.map(dto, OrdersEntity.class);
|
||||
entity.setProduct(productsService.get(dto.getProductId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<OrdersDto> getAll(@PathVariable(name = "user") Long userId,
|
||||
@RequestParam(name = "productId", defaultValue = "0") ProductsEntity product) {
|
||||
return ordersService.getAll(userId).stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public OrdersDto get(@PathVariable(name = "user") Long userId, @PathVariable(name = "id") Long id) {
|
||||
return toDto(ordersService.get(userId, id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public OrdersDto create(@PathVariable(name = "user") Long userId, @RequestBody @Valid OrdersDto dto) {
|
||||
return toDto(ordersService.create(userId, toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public OrdersDto update(@PathVariable(name = "user") Long userId, @PathVariable(name = "id") Long id,
|
||||
@RequestBody OrdersDto dto) {
|
||||
return toDto(ordersService.update(userId, id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public OrdersDto delete(@PathVariable(name = "user") Long userId, @PathVariable(name = "id") Long id) {
|
||||
return toDto(ordersService.delete(userId, id));
|
||||
}
|
||||
}
|
67
src/main/java/com/example/demo/orders/api/OrdersDto.java
Normal file
67
src/main/java/com/example/demo/orders/api/OrdersDto.java
Normal file
@ -0,0 +1,67 @@
|
||||
package com.example.demo.orders.api;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class OrdersDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotNull
|
||||
private ProductsEntity product;
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer count;
|
||||
@NotNull
|
||||
private Date date;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public ProductsEntity getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
public void setProduct(ProductsEntity product) {
|
||||
this.product = product;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return product.getId();
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
productId = product.getId();
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Double getSum() {
|
||||
return count * product.getPrice();
|
||||
}
|
||||
|
||||
}
|
117
src/main/java/com/example/demo/orders/model/OrdersEntity.java
Normal file
117
src/main/java/com/example/demo/orders/model/OrdersEntity.java
Normal file
@ -0,0 +1,117 @@
|
||||
package com.example.demo.orders.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.users.model.UsersEntity;
|
||||
|
||||
import jakarta.persistence.Temporal;
|
||||
import jakarta.persistence.TemporalType;
|
||||
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 OrdersEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "productId", nullable = false)
|
||||
private ProductsEntity product;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UsersEntity user;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer count;
|
||||
|
||||
private Double sum;
|
||||
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Date date;
|
||||
|
||||
public Date StringConvertDate(String date) {
|
||||
SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy");
|
||||
try {
|
||||
return formater.parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public OrdersEntity() {
|
||||
}
|
||||
|
||||
public OrdersEntity(ProductsEntity product, Integer count, String date) {
|
||||
this.product = product;
|
||||
this.count = count;
|
||||
this.sum = getSum();
|
||||
this.date = StringConvertDate(date);
|
||||
}
|
||||
|
||||
public ProductsEntity getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
public void setProduct(ProductsEntity product) {
|
||||
this.product = product;
|
||||
}
|
||||
|
||||
public UsersEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UsersEntity user) {
|
||||
this.user = user;
|
||||
if (!user.getOrders().contains(this)) {
|
||||
user.getOrders().add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public Double getSum() {
|
||||
sum = count * product.getPrice();
|
||||
return sum;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, product, count);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final OrdersEntity other = (OrdersEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getProduct(), product)
|
||||
&& Objects.equals(other.getUser().getId(), user.getId())
|
||||
&& Objects.equals(other.getCount(), count)
|
||||
&& Objects.equals(other.getDate(), date);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.example.demo.orders.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.orders.model.OrdersEntity;
|
||||
|
||||
public interface OrdersRepository extends CrudRepository<OrdersEntity, Long> {
|
||||
Optional<OrdersEntity> findOneByUserIdAndId(long userId, long id);
|
||||
|
||||
List<OrdersEntity> findByUserId(long userId);
|
||||
|
||||
// select
|
||||
// tpe.name,
|
||||
// coalesce(sum(order.price), 0),
|
||||
// coalesce(sum(order.count), 0)
|
||||
// from types as tpe
|
||||
// left join orders as order on tpe.id = order.type_id and order.user_id = ?
|
||||
// group by tpe.name order by tpe.id
|
||||
// @Query("select "
|
||||
// + "u as user, "
|
||||
// + "coalesce(sum(o.sum), 0) as totalSum, "
|
||||
// + "coalesce(sum(o.count), 0) as totalCount "
|
||||
// + "from UsersEntity u left join OrderEntity o on o.user = u and o.user.id =
|
||||
// ?1 "
|
||||
// + "group by u order by u.id")
|
||||
// List<OrdersGrouped> getOrdersTotalByUser(long userId);
|
||||
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
package com.example.demo.orders.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.orders.model.OrdersEntity;
|
||||
import com.example.demo.orders.repository.OrdersRepository;
|
||||
import com.example.demo.users.model.UsersEntity;
|
||||
import com.example.demo.users.service.UsersService;
|
||||
|
||||
@Service
|
||||
public class OrdersService {
|
||||
private final OrdersRepository repository;
|
||||
private final UsersService userService;
|
||||
|
||||
public OrdersService(OrdersRepository repository, UsersService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<OrdersEntity> getAll(long userId) {
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public OrdersEntity get(long userId, Long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(OrdersEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrdersEntity create(long userId, OrdersEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
final UsersEntity existsUser = userService.get(userId);
|
||||
entity.setUser(existsUser);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrdersEntity update(long userId, Long id, OrdersEntity entity) {
|
||||
userService.get(userId);
|
||||
final OrdersEntity existsEntity = get(userId, id);
|
||||
existsEntity.setProduct(entity.getProduct());
|
||||
existsEntity.setCount(entity.getCount());
|
||||
existsEntity.setDate(entity.getDate());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrdersEntity delete(long userId, Long id) {
|
||||
userService.get(userId);
|
||||
final OrdersEntity existsEntity = get(userId, id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
// @Transactional(readOnly = true)
|
||||
// public List<OrdersGrouped> getTotal(long userId) {
|
||||
// //userService.get(userId);
|
||||
// return repository.getOrdersTotalByUser(userId);
|
||||
// }
|
||||
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
package com.example.demo.products.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.configuration.Constants;
|
||||
import com.example.demo.categories.service.CategoriesService;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.products.service.ProductsService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/Products")
|
||||
public class ProductsController {
|
||||
private final ProductsService productsService;
|
||||
private final CategoriesService categoriesService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public ProductsController(ProductsService productsService, CategoriesService categoriesService,
|
||||
ModelMapper modelMapper) {
|
||||
this.productsService = productsService;
|
||||
this.categoriesService = categoriesService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private ProductsDto toDto(ProductsEntity entity) {
|
||||
return modelMapper.map(entity, ProductsDto.class);
|
||||
}
|
||||
|
||||
private ProductsEntity toEntity(ProductsDto dto) {
|
||||
final ProductsEntity entity = modelMapper.map(dto, ProductsEntity.class);
|
||||
entity.setType(categoriesService.get(dto.getTypeId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ProductsDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId) {
|
||||
return productsService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ProductsDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(productsService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ProductsDto create(@RequestBody @Valid ProductsDto dto) {
|
||||
return toDto(productsService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ProductsDto update(@PathVariable(name = "id") Long id, @RequestBody ProductsDto dto) {
|
||||
return toDto(productsService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ProductsDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(productsService.delete(id));
|
||||
}
|
||||
}
|
53
src/main/java/com/example/demo/products/api/ProductsDto.java
Normal file
53
src/main/java/com/example/demo/products/api/ProductsDto.java
Normal file
@ -0,0 +1,53 @@
|
||||
package com.example.demo.products.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ProductsDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
private String name;
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long categoryId;
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Double price;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getTypeId() {
|
||||
return categoryId;
|
||||
}
|
||||
|
||||
public void setTypeId(Long categoryId) {
|
||||
this.categoryId = categoryId;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package com.example.demo.products.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.categories.model.CategoriesEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "products")
|
||||
public class ProductsEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "categoryId", nullable = false)
|
||||
private CategoriesEntity category;
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private Double price;
|
||||
|
||||
public ProductsEntity() {
|
||||
}
|
||||
|
||||
public ProductsEntity(CategoriesEntity category, String name, Double price) {
|
||||
this.category = category;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public CategoriesEntity getType() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setType(CategoriesEntity category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, category, name, price);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final ProductsEntity other = (ProductsEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getType(), category)
|
||||
&& Objects.equals(other.getName(), name)
|
||||
&& Objects.equals(other.getPrice(), price);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.example.demo.products.repository;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
|
||||
public interface ProductsRepository extends CrudRepository<ProductsEntity, Long> {
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.example.demo.products.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.products.model.ProductsEntity;
|
||||
import com.example.demo.products.repository.ProductsRepository;
|
||||
|
||||
@Service
|
||||
public class ProductsService {
|
||||
private final ProductsRepository repository;
|
||||
|
||||
public ProductsService(ProductsRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ProductsEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ProductsEntity get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new NotFoundException(ProductsEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductsEntity create(ProductsEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductsEntity update(Long id, ProductsEntity entity) {
|
||||
final ProductsEntity existsEntity = get(id);
|
||||
existsEntity.setType(entity.getType());
|
||||
existsEntity.setName(entity.getName());
|
||||
existsEntity.setPrice(entity.getPrice());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductsEntity delete(Long id) {
|
||||
final ProductsEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
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.UsersEntity;
|
||||
import com.example.demo.users.model.UsersGrouped;
|
||||
import com.example.demo.users.service.UsersService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/Users")
|
||||
public class UsersController {
|
||||
private final UsersService usersService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UsersController(UsersService usersService, ModelMapper modelMapper) {
|
||||
this.usersService = usersService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UsersDto toDto(UsersEntity entity) {
|
||||
return modelMapper.map(entity, UsersDto.class);
|
||||
}
|
||||
|
||||
private UsersGroupedDto toGroupedDto(UsersGrouped entity) {
|
||||
return (UsersGroupedDto) this.modelMapper.map(entity, UsersGroupedDto.class);
|
||||
}
|
||||
|
||||
private UsersEntity toEntity(UsersDto dto) {
|
||||
return modelMapper.map(dto, UsersEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<UsersDto> getAll(
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(usersService.getAll(page, size), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UsersDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(usersService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UsersDto create(@RequestBody @Valid UsersDto dto) {
|
||||
return toDto(usersService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UsersDto update(@PathVariable(name = "id") Long id, @RequestBody UsersDto dto) {
|
||||
return toDto(usersService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UsersDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(usersService.delete(id));
|
||||
}
|
||||
|
||||
@GetMapping({ "/total" })
|
||||
public List<UsersGroupedDto> getMethodName() {
|
||||
return this.usersService.getFiveUsers().stream().map(this::toGroupedDto).toList();
|
||||
}
|
||||
}
|
37
src/main/java/com/example/demo/users/api/UsersDto.java
Normal file
37
src/main/java/com/example/demo/users/api/UsersDto.java
Normal file
@ -0,0 +1,37 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class UsersDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
private String login;
|
||||
private String password;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
public class UsersGroupedDto {
|
||||
private Long userId;
|
||||
private Double totalSum;
|
||||
|
||||
public UsersGroupedDto() {
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Double getTotalSum() {
|
||||
return this.totalSum;
|
||||
}
|
||||
|
||||
public void setTotalSum(Double totalSum) {
|
||||
this.totalSum = totalSum;
|
||||
}
|
||||
|
||||
}
|
80
src/main/java/com/example/demo/users/model/UsersEntity.java
Normal file
80
src/main/java/com/example/demo/users/model/UsersEntity.java
Normal file
@ -0,0 +1,80 @@
|
||||
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.OrdersEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UsersEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 20)
|
||||
private String login;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
private String password;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<OrdersEntity> orders = new HashSet<>();
|
||||
|
||||
public UsersEntity() {
|
||||
}
|
||||
|
||||
public UsersEntity(String login, String password) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Set<OrdersEntity> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrder(OrdersEntity order) {
|
||||
if (order.getUser() != this) {
|
||||
order.setUser(this);
|
||||
}
|
||||
orders.add(order);
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, login, password);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final UsersEntity other = (UsersEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getLogin(), login)
|
||||
&& Objects.equals(other.getPassword(), password);
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
public interface UsersGrouped {
|
||||
UsersEntity getUser();
|
||||
|
||||
Double getTotalSum();
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.users.model.UsersEntity;
|
||||
import com.example.demo.users.model.UsersGrouped;
|
||||
|
||||
public interface UsersRepository
|
||||
extends CrudRepository<UsersEntity, Long>, PagingAndSortingRepository<UsersEntity, Long> {
|
||||
|
||||
@Query("SELECT user AS u, SUM(o.sum) AS totalSum " +
|
||||
"FROM OrdersEntity o " +
|
||||
"GROUP BY user " +
|
||||
"ORDER BY totalSum DESC")
|
||||
List<UsersGrouped> getFiveUsersHaveMaxSummPurchase(Pageable limit);
|
||||
|
||||
}
|
||||
|
||||
// вывести 5 пользователей с наибольшей суммой всех покупок на jpql
|
@ -0,0 +1,67 @@
|
||||
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.UsersEntity;
|
||||
import com.example.demo.users.model.UsersGrouped;
|
||||
import com.example.demo.users.repository.UsersRepository;
|
||||
|
||||
@Service
|
||||
public class UsersService {
|
||||
private final UsersRepository repository;
|
||||
|
||||
public UsersService(UsersRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UsersEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UsersEntity> getAll(int page, int size) {
|
||||
return repository.findAll(PageRequest.of(page, size));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UsersEntity get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new NotFoundException(UsersEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UsersEntity create(UsersEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UsersEntity update(Long id, UsersEntity entity) {
|
||||
final UsersEntity existsEntity = get(id);
|
||||
existsEntity.setLogin(entity.getLogin());
|
||||
existsEntity.setPassword(entity.getPassword());
|
||||
repository.save(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UsersEntity delete(Long id) {
|
||||
final UsersEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UsersGrouped> getFiveUsers() {
|
||||
return this.repository.getFiveUsersHaveMaxSummPurchase(PageRequest.of(0, 5));
|
||||
}
|
||||
}
|
@ -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=sa
|
||||
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
|
63
src/test/java/com/example/demo/CategoriesServiceTests.java
Normal file
63
src/test/java/com/example/demo/CategoriesServiceTests.java
Normal file
@ -0,0 +1,63 @@
|
||||
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 com.example.demo.categories.service.CategoriesService;
|
||||
import com.example.demo.categories.model.CategoriesEntity;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class CategoriesServiceTests {
|
||||
@Autowired
|
||||
private CategoriesService categoriesService;
|
||||
|
||||
private CategoriesEntity category;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
category = categoriesService.create(new CategoriesEntity("Ноутбук"));
|
||||
categoriesService.create(new CategoriesEntity("Телефон"));
|
||||
categoriesService.create(new CategoriesEntity("Игровая приставка"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
categoriesService.getAll().forEach(item -> categoriesService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, categoriesService.getAll().size());
|
||||
Assertions.assertEquals(category, categoriesService.get(category.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final CategoriesEntity entity = categoriesService.get(category.getId());
|
||||
final String oldName = entity.getName();
|
||||
final CategoriesEntity newEntity = categoriesService.update(category.getId(), new CategoriesEntity(test));
|
||||
Assertions.assertEquals(3, categoriesService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, categoriesService.get(newEntity.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
categoriesService.delete(category.getId());
|
||||
Assertions.assertEquals(2, categoriesService.getAll().size());
|
||||
|
||||
final CategoriesEntity newEntity = categoriesService.create(new CategoriesEntity("Ноутбук"));
|
||||
Assertions.assertEquals(3, categoriesService.getAll().size());
|
||||
Assertions.assertNotEquals(category.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
@ -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() {
|
||||
}
|
||||
|
||||
}
|
81
src/test/java/com/example/demo/ProductsServiceTests.java
Normal file
81
src/test/java/com/example/demo/ProductsServiceTests.java
Normal file
@ -0,0 +1,81 @@
|
||||
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 com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.categories.model.CategoriesEntity;
|
||||
import com.example.demo.categories.service.CategoriesService;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.products.service.ProductsService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class ProductsServiceTests {
|
||||
@Autowired
|
||||
private ProductsService productsService;
|
||||
@Autowired
|
||||
private CategoriesService categoriesService;
|
||||
|
||||
private ProductsEntity product;
|
||||
|
||||
private CategoriesEntity category1;
|
||||
private CategoriesEntity category2;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
category1 = categoriesService.create(new CategoriesEntity("Телефон"));
|
||||
category2 = categoriesService.create(new CategoriesEntity("Игровая приставка"));
|
||||
product = productsService.create(new ProductsEntity(category1, "Lenovo IDEA PAD 13", 15232.00));
|
||||
productsService.create(new ProductsEntity(category1, "Acer", 20300.00));
|
||||
productsService.create(new ProductsEntity(category2, "Iphone 13", 150000.00));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
productsService.getAll().forEach(item -> productsService.delete(item.getId()));
|
||||
categoriesService.getAll().forEach(item -> categoriesService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> productsService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, productsService.getAll().size());
|
||||
Assertions.assertEquals(product, productsService.get(product.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final Double newPrice = 20000.00;
|
||||
final ProductsEntity entity = productsService.get(product.getId());
|
||||
final Double oldPrice = entity.getPrice();
|
||||
final ProductsEntity newEntity = productsService.update(product.getId(),
|
||||
new ProductsEntity(category1, "Lenovo IDEA PAD 13", newPrice));
|
||||
Assertions.assertEquals(3, productsService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, productsService.get(newEntity.getId()));
|
||||
Assertions.assertEquals(newPrice, newEntity.getPrice());
|
||||
Assertions.assertNotEquals(oldPrice, newEntity.getPrice());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
productsService.delete(product.getId());
|
||||
Assertions.assertEquals(2, productsService.getAll().size());
|
||||
|
||||
final ProductsEntity newEntity = productsService
|
||||
.create(new ProductsEntity(category1, "Lenovo IDEA PAD 13", 15232.00));
|
||||
Assertions.assertEquals(3, productsService.getAll().size());
|
||||
Assertions.assertNotEquals(product.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
151
src/test/java/com/example/demo/UsersOrdersServiceTests.java
Normal file
151
src/test/java/com/example/demo/UsersOrdersServiceTests.java
Normal file
@ -0,0 +1,151 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
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.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.categories.model.CategoriesEntity;
|
||||
import com.example.demo.categories.service.CategoriesService;
|
||||
import com.example.demo.orders.model.OrdersEntity;
|
||||
import com.example.demo.orders.service.OrdersService;
|
||||
import com.example.demo.products.model.ProductsEntity;
|
||||
import com.example.demo.products.service.ProductsService;
|
||||
import com.example.demo.users.model.UsersEntity;
|
||||
import com.example.demo.users.service.UsersService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UsersOrdersServiceTests {
|
||||
@Autowired
|
||||
private UsersService usersService;
|
||||
@Autowired
|
||||
private OrdersService ordersService;
|
||||
@Autowired
|
||||
private ProductsService productsService;
|
||||
@Autowired
|
||||
private CategoriesService categoriesService;
|
||||
|
||||
private UsersEntity user1;
|
||||
private UsersEntity user2;
|
||||
|
||||
private ProductsEntity product;
|
||||
private CategoriesEntity category;
|
||||
private OrdersEntity order;
|
||||
private SimpleDateFormat formater = new SimpleDateFormat("dd.MM.yyyy");
|
||||
|
||||
public String DateConvertString(Date date) {
|
||||
return formater.format(date);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
category = categoriesService.create(new CategoriesEntity("Телефон"));
|
||||
|
||||
product = productsService.create(new ProductsEntity(category, "Iphone 13", 1000.00));
|
||||
|
||||
user1 = usersService.create(new UsersEntity("Natalia", "1234"));
|
||||
user2 = usersService.create(new UsersEntity("Revengel", "4567"));
|
||||
|
||||
final var orders = List.of(
|
||||
new OrdersEntity(product, 3, "03.04.2024"),
|
||||
new OrdersEntity(product, 2, "02.04.2024"),
|
||||
new OrdersEntity(product, 1, "05.04.2024"),
|
||||
new OrdersEntity(product, 4, "03.04.2024"));
|
||||
orders.forEach(order -> ordersService.create(user1.getId(), order));
|
||||
final var orders2 = List.of(
|
||||
new OrdersEntity(product, 1, "03.04.2024"),
|
||||
new OrdersEntity(product, 1, "02.04.2024"),
|
||||
new OrdersEntity(product, 1, "05.04.2024"),
|
||||
new OrdersEntity(product, 1, "03.04.2024"));
|
||||
orders2.forEach(order -> ordersService.create(user2.getId(), order));
|
||||
// order = ordersService.get(user1.getId(), 1);
|
||||
order = orders.get(0);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
usersService.getAll().forEach(item -> usersService.delete(item.getId()));
|
||||
productsService.getAll().forEach(item -> productsService.delete(item.getId()));
|
||||
categoriesService.getAll().forEach(item -> categoriesService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOrderTest() {
|
||||
Assertions.assertEquals(4, ordersService.getAll(user1.getId()).size());
|
||||
Assertions.assertEquals(0, ordersService.getAll(user2.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserTest() {
|
||||
Assertions.assertEquals(2, usersService.getAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOrderTest() {
|
||||
final Integer newCount = 5;
|
||||
final OrdersEntity entity = ordersService.get(user1.getId(), order.getId());
|
||||
final Integer oldCount = entity.getCount();
|
||||
final Date dateEntity = entity.getDate();
|
||||
final OrdersEntity newEntity = ordersService.update(user1.getId(), order.getId(),
|
||||
new OrdersEntity(product, newCount, DateConvertString(dateEntity)));
|
||||
Assertions.assertEquals(4, ordersService.getAll(user1.getId()).size());
|
||||
Assertions.assertEquals(newEntity,
|
||||
ordersService.get(user1.getId(), newEntity.getId()));
|
||||
Assertions.assertEquals(newCount, newEntity.getCount());
|
||||
Assertions.assertNotEquals(oldCount, newEntity.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserTest() {
|
||||
final String newPassword = "0000";
|
||||
final UsersEntity entity = usersService.get(user1.getId());
|
||||
final String login = entity.getLogin();
|
||||
final String oldPassword = entity.getPassword();
|
||||
final UsersEntity newEntity = usersService.update(user1.getId(), new UsersEntity(login, newPassword));
|
||||
Assertions.assertEquals(2, usersService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, usersService.get(newEntity.getId()));
|
||||
Assertions.assertEquals(newPassword, newEntity.getPassword());
|
||||
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteOrderTest() {
|
||||
ordersService.delete(user1.getId(), order.getId());
|
||||
Assertions.assertEquals(3, ordersService.getAll(user1.getId()).size());
|
||||
|
||||
final OrdersEntity newEntity = ordersService.create(user1.getId(), new OrdersEntity(product, 3, "03.04.2024"));
|
||||
Assertions.assertEquals(4, ordersService.getAll(user1.getId()).size());
|
||||
Assertions.assertNotEquals(order.getId(), newEntity.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUserTest() {
|
||||
usersService.delete(user1.getId());
|
||||
Assertions.assertEquals(1, usersService.getAll().size());
|
||||
|
||||
final UsersEntity newEntity = usersService.create(new UsersEntity("Natalia",
|
||||
"1234"));
|
||||
Assertions.assertEquals(2, usersService.getAll().size());
|
||||
Assertions.assertNotEquals(user1.getId(), newEntity.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFiveUsersTest() {
|
||||
|
||||
Assertions.assertEquals(2, usersService.getFiveUsers().size());
|
||||
final Double sum2 = usersService.getFiveUsers().get(1).getTotalSum();
|
||||
Assertions.assertEquals(4000, sum2);
|
||||
}
|
||||
|
||||
}
|
14
src/test/resources/application.properties
Normal file
14
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=sa
|
||||
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…
Reference in New Issue
Block a user