begin lab3

This commit is contained in:
revengel66 2024-04-19 23:41:02 +04:00
parent 7369280716
commit 6b9a2025ed
21 changed files with 244 additions and 131 deletions

View File

@ -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'
}
@ -21,6 +32,9 @@ dependencies {
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'
}

View File

@ -1,6 +1,8 @@
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";
private Constants() {

View File

@ -1,7 +1,7 @@
package com.example.demo.core.error;
public class NotFoundException extends RuntimeException {
public NotFoundException(Long id) {
super(String.format("Entity with id [%s] is not found or not exists", id));
public <T> NotFoundException(Class<T> clazz, Long id) {
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
}
}

View File

@ -1,6 +1,18 @@
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() {

View File

@ -1,17 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -1,57 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -2,7 +2,15 @@ package com.example.demo.itemCategories.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 = "сategories")
public class CategoriesEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
public CategoriesEntity() {

View File

@ -1,10 +1,11 @@
package com.example.demo.itemCategories.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.itemCategories.model.CategoriesEntity;
@Repository
public class CategoriesRepository extends MapRepository<CategoriesEntity> {
public interface CategoriesRepository extends CrudRepository<CategoriesEntity, Long> {
Optional<CategoriesEntity> findByNameIgnoreCase(String name);
}

View File

@ -1,14 +1,16 @@
package com.example.demo.itemCategories.service;
import java.util.List;
import java.util.Optional;
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.itemCategories.model.CategoriesEntity;
import com.example.demo.itemCategories.repository.CategoriesRepository;
@Service
public class CategoriesService {
private final CategoriesRepository repository;
@ -16,27 +18,31 @@ public class CategoriesService {
public CategoriesService(CategoriesRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<CategoriesEntity> getAll() {
return repository.getAll();
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public CategoriesEntity get(Long id) {
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id));
return repository.findById(id).orElseThrow(() -> new NotFoundException(CategoriesEntity.class, id));
}
@Transactional
public CategoriesEntity create(CategoriesEntity entity) {
return repository.create(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.update(existsEntity);
return repository.save(existsEntity);
}
@Transactional
public CategoriesEntity delete(Long id) {
final CategoriesEntity existsEntity = get(id);
return repository.delete(existsEntity);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.itemOrders.model.OrdersEntity;
import com.example.demo.itemOrders.model.OrdersGrouped;
import com.example.demo.itemOrders.service.OrdersService;
import com.example.demo.itemProducts.model.ProductsEntity;
import com.example.demo.itemProducts.service.ProductsService;
@ -22,7 +23,7 @@ import com.example.demo.itemProducts.service.ProductsService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/Orders")
@RequestMapping(Constants.API_URL + "/user/{user}/order")
public class OrdersController {
private final OrdersService ordersService;
private final ProductsService productsService;
@ -37,7 +38,9 @@ public class OrdersController {
private OrdersDto toDto(OrdersEntity entity) {
return modelMapper.map(entity, OrdersDto.class);
}
private OrdersGroupedDto toGroupedDto(OrdersGrouped entity) {
return modelMapper.map(entity, OrdersGroupedDto.class);
}
private OrdersEntity toEntity(OrdersDto dto) {
final OrdersEntity entity = modelMapper.map(dto, OrdersEntity.class);
entity.setProduct(productsService.get(dto.getProductId()));
@ -45,27 +48,32 @@ public class OrdersController {
}
@GetMapping
public List<OrdersDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") ProductsEntity product) {
return ordersService.getAll(product.getId()).stream().map(this::toDto).toList();
public List<OrdersDto> getAll(@PathVariable(name = "user") Long userId, @RequestParam(name = "typeId", defaultValue = "0") ProductsEntity product) {
return ordersService.getAll(userId, categoryId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public OrdersDto get(@PathVariable(name = "id") Long id) {
return toDto(ordersService.get(id));
public OrdersDto get(@PathVariable(name = "user") Long userId, @PathVariable(name = "id") Long id) {
return toDto(ordersService.get(userId, id));
}
@PostMapping
public OrdersDto create(@RequestBody @Valid OrdersDto dto) {
return toDto(ordersService.create(toEntity(dto)));
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 = "id") Long id, @RequestBody OrdersDto dto) {
return toDto(ordersService.update(id, toEntity(dto)));
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 = "id") Long id) {
return toDto(ordersService.delete(id));
public OrdersDto delete(@PathVariable(name = "user") Long userId, @PathVariable(name = "id") Long id) {
return toDto(ordersService.delete(userId, id));
}
@GetMapping("/total")
public List<OrdersGroupedDto> getMethodName(@PathVariable(name = "user") Long userId) {
return ordersService.getTotal(userId).stream().map(this::toGroupedDto).toList();
}
}

View File

@ -0,0 +1,32 @@
package com.example.demo.itemOrders.api;
public class OrdersGroupedDto {
private Long categoryId;
private Long totalSum;
private Integer totalCount;
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public Long getTotalSum() {
return totalSum;
}
public void setTotalSum(Long totalSum) {
this.totalSum = totalSum;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
}

View File

@ -3,11 +3,34 @@ import java.text.SimpleDateFormat;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.itemProducts.model.ProductsEntity;
import com.example.demo.itemUsers.model.UsersEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
@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;
@Temporal(TemporalType.DATE)
private SimpleDateFormat date;
@Column(nullable = false)
private Double sum;
public OrdersEntity() {
@ -25,6 +48,16 @@ public class OrdersEntity extends BaseEntity {
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;

View File

@ -0,0 +1,11 @@
package com.example.demo.itemOrders.model;
import com.example.demo.itemCategories.model.CategoriesEntity;
public interface OrdersGrouped {
CategoriesEntity getCategory();
double getTotalSum();
int getTotalCount();
}

View File

@ -1,10 +1,13 @@
package com.example.demo.itemOrders.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.itemOrders.model.OrdersEntity;
@Repository
public class OrdersRepository extends MapRepository<OrdersEntity> {
public interface OrdersRepository extends CrudRepository<OrdersEntity, Long> {
Optional<OrdersEntity> findOneByUserIdAndId(long userId, long id);
List<OrdersEntity> findByUserId(long userId);
}

View File

@ -9,16 +9,18 @@ import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.itemOrders.model.OrdersEntity;
import com.example.demo.itemOrders.repository.OrdersRepository;
import com.example.demo.itemUsers.service.UsersService;
@Service
public class OrdersService {
private final OrdersRepository repository;
private final UsersService userService;
public OrdersService(OrdersRepository repository) {
public OrdersService(OrdersRepository repository, UsersService userService) {
this.repository = repository;
this.userService = userService;
}
/* */
public List<OrdersEntity> getAll(Long productId) {
if (Objects.equals(productId, 0L)) {
return repository.getAll();

View File

@ -5,9 +5,21 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.itemCategories.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 type;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Double price;
public ProductsEntity(Object object, String string) {

View File

@ -1,11 +1,11 @@
package com.example.demo.itemProducts.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.itemProducts.model.ProductsEntity;
@Repository
public class ProductsRepository extends MapRepository<ProductsEntity>{
public interface ProductsRepository extends CrudRepository<ProductsEntity, Long> {
Optional<ProductsEntity> findByNameIgnoreCase(String name);
}

View File

@ -1,9 +1,10 @@
package com.example.demo.itemProducts.service;
import java.util.List;
import java.util.Optional;
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.itemProducts.model.ProductsEntity;
@ -17,21 +18,14 @@ public class ProductsService {
this.repository = repository;
}
/*
* public List<ProductsEntity> getAll(Long typeId) {
* if (Objects.equals(typeId, 0L)) {
* return repository.getAll();
* }
* return repository.getAll().stream().filter(item ->
* item.getType().getId().equals(typeId)).toList();
* }
*/
@Transactional(readOnly = true)
public List<ProductsEntity> getAll() {
return repository.getAll();
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
public ProductsEntity get(Long id) {
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id));
return repository.findById(id).orElseThrow(() -> new NotFoundException(ProductsEntity.class, id));
}
public ProductsEntity create(ProductsEntity entity) {

View File

@ -1,11 +1,30 @@
package com.example.demo.itemUsers.model;
import java.util.Objects;
import java.util.Set;
import java.util.HashSet;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.itemOrders.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() {
super();
}
@ -15,7 +34,17 @@ public class UsersEntity extends BaseEntity {
this.login = login;
this.password = password;
}
public Set<OrdersEntity> getOrders() {
return orders;
}
public void addOrder(OrdersEntity order) {
if (order.getUser() != this) {
order.setUser(this);
}
orders.add(order);
}
public String getLogin() {
return login;
}

View File

@ -1,10 +1,11 @@
package com.example.demo.itemUsers.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.itemUsers.model.UsersEntity;
@Repository
public class UsersRepository extends MapRepository<UsersEntity> {
public interface UsersRepository extends CrudRepository<UsersEntity, Long> {
Optional<UsersEntity> findByNameIgnoreCase(String name);
}

View File

@ -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