Compare commits

...

11 Commits
main ... lab3

45 changed files with 2094 additions and 174 deletions

View File

@ -1,26 +1,43 @@
plugins { plugins {
id 'java' id 'java'
id 'org.springframework.boot' version '3.2.2' id 'org.springframework.boot' version '3.2.4'
id 'io.spring.dependency-management' version '1.1.4' id 'io.spring.dependency-management' version '1.1.4'
} }
group = 'com.example' group = 'com.example'
version = '0.0.1-SNAPSHOT' 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 { java {
sourceCompatibility = '17' sourceCompatibility = '17'
} }
repositories { repositories {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' 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.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0' implementation 'org.modelmapper:modelmapper:3.2.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'} implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') { tasks.named('test') {
useJUnitPlatform() useJUnitPlatform()

BIN
data.mv.db Normal file

Binary file not shown.

View File

@ -1,46 +0,0 @@
package com.example.demo;
import java.util.List;
import java.util.ArrayList;
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/genre")
public class ApiController {
private final List<GenreDto> genres = new ArrayList<>();
@PostMapping
public boolean createGenre(@RequestBody GenreDto value){
return genres.add(value);
}
@GetMapping
public List<GenreDto> getAll(){
return genres;
}
@GetMapping("/{id}")
public GenreDto getGenre(@PathVariable(name = "id") int id){
return genres.get(id);
}
@DeleteMapping("/{id}")
public GenreDto delGenre(@PathVariable(name = "id") int id){
return genres.remove(id);
}
@PutMapping
public boolean updGenre(@RequestBody GenreDto genreDto){
genres.remove(genreDto.getId());
return genres.add(genreDto);
}
}

View File

@ -1,17 +1,75 @@
package com.example.demo; package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
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 @SpringBootApplication
@RestController public class DemoApplication implements CommandLineRunner {
@RequestMapping("/api") private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
public class DemoApplication {
private final TypeService typeService;
private final GenreService genreService;
private final GameService gameService;
private final OrderService orderService;
private final UserService userService;
public DemoApplication(TypeService typeService, GenreService genreService, GameService gameService, OrderService orderService, UserService userService){
this.typeService = typeService;
this.gameService = gameService;
this.genreService = genreService;
this.orderService = orderService;
this.userService = userService;
}
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args); SpringApplication.run(DemoApplication.class, args);
} }
@Override
public void run(String... args) throws Exception{
log.info("start");
// final var type1 = typeService.create(new TypeEntity("ААА"));
// final var type2 = typeService.create(new TypeEntity("АА"));
// final var genre1 = genreService.create(new GenreEntity("Приключения"));
// final var genre2 = genreService.create(new GenreEntity("Симулятор"));
// final List<GenreEntity> genres1 = new ArrayList<GenreEntity>();
// genres1.add(genre1);
// genres1.add(genre2);
// final List<GenreEntity> genres2 = new ArrayList<GenreEntity>();
// genres2.add(genre2);
// final var game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1));
// final var game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2));
// final List<GameEntity> games = new ArrayList<GameEntity>();
// games.add(game1);
// games.add(game2);
// var user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123"));
// var user2 = userService.create(new UserEntity( "login2", "email@gmail.com", "qwerty1234"));
// orderService.create(7, new OrderEntity(user1,games));
// orderService.create(8, new OrderEntity(user2,games));
}
} }

View File

@ -1,26 +0,0 @@
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class GenreDto {
private int id;
private String name;
public GenreDto(){
}
@JsonCreator
public GenreDto(@JsonProperty(value="id") int id,
@JsonProperty(value="name") String name){
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
}

View File

@ -1,15 +0,0 @@
package com.example.demo;
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;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View 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;
}
}

View 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;
}
}

View File

@ -1,7 +1,9 @@
package com.example.demo.core.configuration; package com.example.demo.core.configuration;
public class Constants { public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0"; public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() { private Constants() {
} }

View File

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

View File

@ -1,15 +1,23 @@
package com.example.demo.core.model; 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 { 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 Long id;
protected BaseEntity() { protected BaseEntity() {
} }
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() { public Long getId() {
return id; return id;
} }

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

@ -0,0 +1,94 @@
package com.example.demo.games.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.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/game")
public class GameController {
private final GameService gameService;
private final TypeService typeService;
private final GenreService genreService;
private final ModelMapper modelMapper;
public GameController(GameService gameService, TypeService typeService, GenreService genreService, ModelMapper modelMapper){
this.gameService = gameService;
this.genreService = genreService;
this.modelMapper = modelMapper;
this.typeService = typeService;
}
private GameDto toDto(GameEntity entity){
//return modelMapper.map(entity, GameDto.class);
var dto = new GameDto();
dto.setId(entity.getId());
dto.setGenres(entity.getGenres().stream().map(GenreEntity::getId).toList());
dto.setDescription(entity.getDescription());
dto.setName(entity.getName());
dto.setPrice(entity.getPrice());
dto.setTypeId(entity.getType().getId());
return dto;
}
private GameEntity toEntity(GameDto dto){
final GameEntity entity = modelMapper.map(dto, GameEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
var genres = dto.getGenres();
List<GenreEntity> genresList = genreService.getAllById(genres);
for(var genre : genresList){
entity.setGenres(genre);
}
return entity;
}
@GetMapping
public PageDto<GameDto> getAll(
@RequestParam(name = "typeId", defaultValue = "0") long typeId,
//@RequestParam(name = "genres", defaultValue = "") List<Long> genres,
@RequestParam(name = "genreId", defaultValue = "0") long genre,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size){
return PageDtoMapper.toDto(gameService.getAll(typeId, genre, page, size), this::toDto);
}
@GetMapping("/{id}")
public GameDto get(@PathVariable(name = "id") Long id){
return toDto(gameService.get(id));
}
@PostMapping
public GameDto create(@RequestBody @Valid GameDto dto){
return toDto(gameService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public GameDto update(@PathVariable(name = "id") Long id, @RequestBody GameDto dto){
return toDto(gameService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public GameDto delete(@PathVariable(name = "id") Long id){
return toDto(gameService.delete(id));
}
}

View File

@ -0,0 +1,77 @@
package com.example.demo.games.api;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class GameDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long typeId;
@NotNull
private final List<Long> genres = new ArrayList<>();
@NotNull
@Min(1)
private Double price;
@NotBlank
private String name;
@NotBlank
private String description;
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 List<Long> getGenres(){
return genres;
}
public void setGenres(List<Long> genres){
this.genres.clear();
this.genres.addAll(genres);
}
public Double getPrice(){
return price;
}
public void setPrice(Double price){
this.price = price;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
}

View File

@ -0,0 +1,105 @@
package com.example.demo.games.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.types.model.TypeEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "games")
public class GameEntity extends BaseEntity{
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Double price;
@Column(nullable = false)
private String description;
@ManyToMany()
@Column(unique = false)
private final List<GenreEntity> genres = new ArrayList<>();
@OneToOne
@JoinColumn(name = "typeId", nullable = false, unique = false)
private TypeEntity type;
public GameEntity(){
}
public GameEntity(TypeEntity type, String name, Double price, String description, List<GenreEntity> genres){
this.type = type;
this.name = name;
this.price = price;
this.description = description;
this.genres.clear();
this.genres.addAll(genres);
}
public TypeEntity getType(){
return type;
}
public void setType(TypeEntity type){
this.type = type;
}
public Double getPrice(){
return price;
}
public void setPrice(Double price){
this.price = price;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public List<GenreEntity> getGenres(){
return genres;
}
public void setGenres(GenreEntity genre){
this.genres.add(genre);
}
@Override
public int hashCode() {
return Objects.hash(id, type, price, genres, description, name);
}
@Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null || getClass() != obj.getClass())
return false;
final GameEntity other = (GameEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getType(), type)
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getGenres(), genres)
&& Objects.equals(other.getDescription(), description)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +1,63 @@
package com.example.demo.games.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.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.games.model.GameEntity;
public interface GameRepository extends CrudRepository<GameEntity, Long>, PagingAndSortingRepository<GameEntity, Long> {
@Query("select distinct g from GameEntity g join fetch g.genres ge join fetch g.type ty where g.id = ?1")
Optional<GameEntity> findOneById(long id);
@Query("select distinct g from GameEntity g join fetch g.genres ge join fetch g.type ty where ge.id = ?2 and ty.id = ?1")
Page<GameEntity> findByTypeIdAndGenres(long typeId, long genreId, Pageable pageable);
@Query("select distinct g from GameEntity g join fetch g.genres ge join fetch g.type ty where ge.id = ?2 and ty.id = ?1")
List<GameEntity> findByTypeIdAndGenres(long typeId, long genreId);
@Query("select distinct g from GameEntity g join fetch g.type ty where ty.id = ?1")
Page<GameEntity> findByTypeId(long typeId, Pageable pageable);
@Query("select distinct g from GameEntity g join fetch g.type ty where ty.id = ?1")
List<GameEntity> findByTypeId(long typeId);
@Query("select distinct g from GameEntity g join fetch g.genres ge where ge.id = ?1")
Page<GameEntity> findByGenres(long genre, Pageable pageable);
@Query("select distinct g from GameEntity g join fetch g.genres ge where ge.id = ?1")
List<GameEntity> findByGenres(long genre);
@Query("select distinct g from GameEntity g join fetch g.genres join fetch g.type ty")
Page<GameEntity>findAll(Pageable pageable);
@Query("select distinct g from GameEntity g join fetch g.genres join fetch g.type ty")
List<GameEntity>findAll();
}
/* "select "
+ "ga.id, ga.description, ga.name, ga.price, ga.type_id "
+ "from games ga left join fetch games_genres g on ga.id = g.game_entity_id "
+ "where g.id = ?1 "
+ "order by ga.id"*/
//select ge1_0.id,ge1_0.name from genres ge1_0 where ge1_0.id=?
//select ge1_0.id,ge1_0.description,ge1_0.name,ge1_0.price,ge1_0.type_id
//from games ge1_0 left join games_genres g1_0 on ge1_0.id=g1_0.game_entity_id
//where g1_0.genres_id=? offset ? rows fetch first ? rows only
//select te1_0.id,te1_0.name from types te1_0 where te1_0.id=?
//select g1_0.game_entity_id,g1_1.id,g1_1.name from games_genres g1_0 join genres g1_1 on g1_1.id=g1_0.genres_id where g1_0.game_entity_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);

View File

@ -0,0 +1,89 @@
package com.example.demo.games.service;
import java.util.List;
//import java.util.List;
import java.util.Objects;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Pageable;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.repository.GameRepository;
import com.example.demo.genres.service.GenreService;
@Service
public class GameService {
private final GameRepository repository;
public GameService(GameRepository repository, GenreService genreService){
this.repository = repository;
}
@Transactional(readOnly = true)
public List<GameEntity> getAll(long typeId, long genre){
if(!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.findByTypeIdAndGenres(typeId, genre);
}
if(Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.findByGenres(genre);
}
if(!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)){
return repository.findByTypeId(typeId);
}
return repository.findAll();
}
@Transactional(readOnly = true)
public Page<GameEntity> getAll(long typeId, long genre, int page, int size){
final Pageable pageRequest = PageRequest.of(page, size);
if(!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.findByTypeIdAndGenres(typeId, genre, pageRequest);
}
if(Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.findByGenres(genre, pageRequest);
}
if(!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)){
return repository.findByTypeId(typeId, pageRequest);
}
return repository.findAll(pageRequest);
}
@Transactional(readOnly = true)
public GameEntity get(Long id){
return repository.findOneById(id).orElseThrow(() -> new NotFoundException(GameEntity.class, id));
}
@Transactional
public GameEntity create(GameEntity entity){
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public GameEntity update(Long id, GameEntity entity){
final GameEntity existEntity = get(id);
existEntity.setName(entity.getName());
existEntity.setPrice(entity.getPrice());
existEntity.setDescription(entity.getDescription());
existEntity.setType(entity.getType());
var genres = entity.getGenres();
for(var genre : genres){
existEntity.setGenres(genre);
}
return repository.save(existEntity);
}
@Transactional
public GameEntity delete(Long id){
final GameEntity existEntity = get(id);
repository.delete(existEntity);
return existEntity;
}
}

View File

@ -0,0 +1,64 @@
package com.example.demo.genres.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.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/genre")
public class GenreController {
private final GenreService genreService;
private final ModelMapper modelMapper;
public GenreController(GenreService genreService, ModelMapper modelMapper){
this.genreService = genreService;
this.modelMapper = modelMapper;
}
private GenreDto toDto(GenreEntity entity){
return modelMapper.map(entity, GenreDto.class);
}
private GenreEntity toEntity(GenreDto dto){
return modelMapper.map(dto, GenreEntity.class);
}
@GetMapping
public List<GenreDto> getAll(){
return genreService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public GenreDto get(@PathVariable(name="id") Long id){
return toDto(genreService.get(id));
}
@PostMapping
public GenreDto create(@RequestBody @Valid GenreDto dto){
return toDto(genreService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public GenreDto update(@PathVariable(name="id") Long id, @RequestBody GenreDto dto){
return toDto(genreService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public GenreDto delete(@PathVariable(name="id") Long id){
return toDto(genreService.delete(id));
}
}

View File

@ -0,0 +1,30 @@
package com.example.demo.genres.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class GenreDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 1, 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;
}
}

View File

@ -0,0 +1,46 @@
package com.example.demo.genres.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 = "genres")
public class GenreEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
public GenreEntity(){
}
public GenreEntity(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 GenreEntity other = (GenreEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.genres.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.genres.model.GenreEntity;
public interface GenreRepository extends CrudRepository<GenreEntity, Long> {
Optional<GenreEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,58 @@
package com.example.demo.genres.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.StreamSupport;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.repository.GenreRepository;
@Service
public class GenreService {
private final GenreRepository repository;
public GenreService(GenreRepository repository){
this.repository = repository;
}
@Transactional(readOnly = true)
public List<GenreEntity> getAll(){
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public List<GenreEntity> getAllById(List<Long> listIds){
return StreamSupport.stream(repository.findAllById(listIds).spliterator(),false).toList();
}
@Transactional(readOnly = true)
public GenreEntity get(Long id){
return repository.findById(id).orElseThrow(() -> new NotFoundException(GenreEntity.class, id));
}
@Transactional
public GenreEntity create(GenreEntity entity){
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public GenreEntity update(Long id, GenreEntity entity){
final GenreEntity exisEntity = get(id);
exisEntity.setName(entity.getName());
return repository.save(exisEntity);
}
@Transactional
public GenreEntity delete(Long id){
final GenreEntity existEntity = get(id);
repository.delete(existEntity);
return existEntity;
}
}

View File

@ -0,0 +1,83 @@
package com.example.demo.orders.api;
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.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.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.users.service.UserService;
import com.example.demo.core.api.PageDtoMapper;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user/{user}/order")
public class OrderController {
private final GameService gameService;
private final ModelMapper modelMapper;
private final OrderService orderService;
public OrderController(GameService gameService, ModelMapper modelMapper, OrderService orderService, UserService userService){
this.gameService = gameService;
this.modelMapper = modelMapper;
this.orderService = orderService;
}
private OrderDto toDto(OrderEntity entity){
var dto = new OrderDto();
dto.setId(entity.getId());
dto.setUserId(entity.getUser().getId());
dto.setGames(entity.getGames().stream().map(GameEntity::getId).toList());
return dto;
}
private OrderEntity toEntity(OrderDto dto){
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
var games = dto.getGames();
for(var game : games){
entity.setGames(gameService.get(game));
}
return entity;
}
@GetMapping
public com.example.demo.core.api.PageDto<OrderDto> getAll(
@RequestParam(name = "userId", defaultValue = "") Long userId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE)int size){
return PageDtoMapper.toDto(orderService.getAll(userId, 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)));
}
@DeleteMapping("/{id}")
public OrderDto delete(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id){
return toDto(orderService.delete(userId, id));
}
}

View File

@ -0,0 +1,42 @@
package com.example.demo.orders.api;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotNull
private final List<Long> games = new ArrayList<>();
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public List<Long> getGames(){
return games;
}
public void setGames(List<Long> games){
this.games.clear();
this.games.addAll(games);
}
public Long getUserId(){
return userId;
}
public void setUserId(Long userId){
this.userId = userId;
}
}

View File

@ -0,0 +1,80 @@
package com.example.demo.orders.model;
import java.util.List;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.games.model.GameEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity{
// @Column(nullable = false)
// private double sum;
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@ManyToMany()
private Set<GameEntity> games = new HashSet<>();
public OrderEntity(){
}
public OrderEntity(UserEntity user, List<GameEntity> games){
this.user = user;
this.games.clear();
this.games.addAll(games);
}
// public double getSum(){
// for(var game : games){
// sum += game.getPrice();
// }
// return sum;
// }
public UserEntity getUser(){
return user;
}
public void setUser(UserEntity user){
this.user = user;
if(!user.getOrders().contains(this)){
user.getOrders().add(this);
}
}
public Set<GameEntity> getGames(){
return games;
}
public void setGames(GameEntity game){
this.games.add(game);
}
@Override
public int hashCode(){
return Objects.hash(id, games);
}
@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.getSum(), sum)
&& Objects.equals(other.getGames(), games);
}
}

View File

@ -0,0 +1,25 @@
package com.example.demo.orders.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.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.orders.model.OrderEntity;
public interface OrderRepository extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
Optional<OrderEntity> findOneByUserIdAndId(long userId, long id);
List<OrderEntity> findByUserId(long userId);
@Query("select o from OrderEntity o join fetch o.games where o.user.id = ?1")
Page<OrderEntity> findByUserId(long userId, Pageable pageable);
List<OrderEntity> findAll();
//Можно сделать запрос на сумму JPQL
}

View File

@ -0,0 +1,67 @@
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.data.domain.Pageable;
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.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 Page<OrderEntity> getAll(long userId, int page, int size){
final Pageable pageRequest = PageRequest.of(page, size);
userService.get(userId);
return repository.findByUserId(userId, pageRequest);
}
@Transactional(readOnly = true)
public List<OrderEntity> getAll(long userId){
userService.get(userId);
return repository.findByUserId(userId);
}
public List<OrderEntity> getAll(){
return repository.findAll();
}
@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 delete(long userId, long id){
userService.get(userId);
final OrderEntity existsEntity = get(userId, id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,64 @@
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;
}
private TypeDto toDto(TypeEntity entity){
return modelMapper.map(entity, TypeDto.class);
}
private TypeEntity toEntity(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 TypeDto dto){
return toDto(typeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public TypeDto delete(@PathVariable(name = "id") Long id){
return toDto(typeService.delete(id));
}
}

View File

@ -0,0 +1,30 @@
package com.example.demo.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 1, 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;
}
}

View File

@ -0,0 +1,46 @@
package com.example.demo.types.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 = "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);
}
}

View File

@ -0,0 +1,12 @@
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);
Optional<TypeEntity> findById(long id);
}

View File

@ -0,0 +1,53 @@
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;
}
@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");
}
return repository.save(entity);
}
@Transactional
public TypeEntity update(Long id, TypeEntity entity){
final TypeEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}
@Transactional
public TypeEntity delete(Long id){
final TypeEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.users.api;
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.service.OrderService;
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 ModelMapper modelMapper;
private final UserService userService;
public UserController(OrderService orderService, ModelMapper modelMapper, UserService userService){
this.modelMapper = modelMapper;
this.userService = userService;
}
private UserDto toDto(UserEntity entity){
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(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 UserDto dto){
return toDto(userService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id")Long id){
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,48 @@
package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 2, max = 20)
private String login;
@NotBlank
@Size(min = 2, max = 20)
private String email;
@NotBlank
@Size(min = 2, max = 20)
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 getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}

View File

@ -0,0 +1,69 @@
package com.example.demo.users.model;
import java.util.ArrayList;
import java.util.List;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity;
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 UserEntity extends BaseEntity{
@Column(nullable = false, unique = true, length = 20)
private String login;
@Column(nullable = false, unique = true, length = 20)
private String email;
@Column(nullable = false, unique = true, length = 20)
private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private List<OrderEntity> orders = new ArrayList<>();
public UserEntity(){
}
public UserEntity(String login, String email, String password){
this.login = login;
this.email = email;
this.password = password;
}
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login = login;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public List<OrderEntity> getOrders(){
return orders;
}
public void addOrder(OrderEntity order){
if(order.getUser() != this){
order.setUser(this);
}
orders.add(order);
}
}

View File

@ -0,0 +1,12 @@
package com.example.demo.users.repository;
import java.util.Optional;
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> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,63 @@
package com.example.demo.users.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
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;
}
@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) {
return repository.findAll(PageRequest.of(page, size));
}
@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");
}
return repository.save(entity);
}
@Transactional
public UserEntity update(Long id, UserEntity entity){
final UserEntity existEntity = get(id);
existEntity.setLogin(entity.getLogin());
existEntity.setEmail(entity.getEmail());
existEntity.setPassword(entity.getPassword());
repository.save(existEntity);
return existEntity;
}
@Transactional
public UserEntity delete(Long id){
final UserEntity existEntity = get(id);
repository.delete(existEntity);
return existEntity;
}
}

View File

@ -1 +1,19 @@
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

View File

@ -0,0 +1,101 @@
package com.example.demo;
import java.util.ArrayList;
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.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GameServiceTests {
@Autowired
private GameService gameService;
@Autowired
private TypeService typeService;
@Autowired
private GenreService genreService;
private GenreEntity genre1;
private GenreEntity genre2;
private TypeEntity type1;
private TypeEntity type2;
private GameEntity game1;
private GameEntity game2;
@BeforeEach
void createData(){
removeData();
genre1 = genreService.create(new GenreEntity("Приключения"));
genre2 = genreService.create(new GenreEntity("Симулятор"));
type1 = typeService.create(new TypeEntity("Игра"));
type2 = typeService.create(new TypeEntity("Программа"));
final List<GenreEntity> genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1);
genres1.add(genre2);
final List<GenreEntity> genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2);
game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1));
game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2));
}
@AfterEach
void removeData(){
gameService.getAll(0,0).forEach(item -> gameService.delete(item.getId()));
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
}
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(2, gameService.getAll(0,0).size());
}
@Test
@Order(2)
void updateTest(){
genre1 = genreService.create(new GenreEntity("Симулятор2"));
type1 = typeService.create(new TypeEntity("Игра2"));
final List<GenreEntity> genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1);
gameService.update(game1.getId(), new GameEntity(type1, "testGame", 1200.0, "hehgame", genres1));
Assertions.assertEquals(2, gameService.getAll(0,0).size());
}
@Test
@Order(3)
void deleteTest(){
gameService.delete(game1.getId());
Assertions.assertEquals(1, gameService.getAll(0,0).size());
final GameEntity last = gameService.get(game2.getId());
Assertions.assertEquals(game2.getId(), last.getId());
}
}

View File

@ -0,0 +1,68 @@
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.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.core.error.NotFoundException;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GenreServiceTests {
@Autowired
private GenreService genreService;
private GenreEntity genre1;
private GenreEntity genre2;
@BeforeEach
void createData(){
removeData();
genre1 = genreService.create(new GenreEntity("Приключения"));
genre2 = genreService.create(new GenreEntity("Симулятор"));
}
@AfterEach
void removeData(){
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
}
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> genreService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(2, genreService.getAll().size());
}
@Test
@Order(2)
void updateTest(){
final String test = "TEST";
final GenreEntity newEntity = genreService.update(genre2.getId(), new GenreEntity(test));
Assertions.assertEquals(2, genreService.getAll().size());
Assertions.assertEquals(newEntity, genreService.get(genre2.getId()));
Assertions.assertEquals(test, newEntity.getName());
}
@Test
@Order(3)
void deleteTest(){
genreService.delete(genre1.getId());
Assertions.assertEquals(1, genreService.getAll().size());
final GenreEntity last = genreService.get(genre2.getId());
Assertions.assertEquals(genre2.getId(), last.getId());
}
}

View File

@ -0,0 +1,130 @@
package com.example.demo;
import java.util.ArrayList;
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.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
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;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class OrderServiceTest {
@Autowired
private GameService gameService;
@Autowired
private TypeService typeService;
@Autowired
private GenreService genreService;
@Autowired
private UserService userService;
@Autowired
private OrderService orderService;
private GenreEntity genre1;
private GenreEntity genre2;
private TypeEntity type1;
private TypeEntity type2;
private List<GenreEntity> genres1 = new ArrayList<>();
private List<GenreEntity> genres2 = new ArrayList<>();
private GameEntity game1;
private GameEntity game2;
private List<GameEntity> games = new ArrayList<>();
private UserEntity user1;
private OrderEntity order1;
@BeforeEach
void createData(){
genre1 = genreService.create(new GenreEntity("Приключения"));
genre2 = genreService.create(new GenreEntity("Симулятор"));
type1 = typeService.create(new TypeEntity("Игра"));
type2 = typeService.create(new TypeEntity("Программа"));
genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1);
genres1.add(genre2);
genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2);
game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1));
game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2));
games = new ArrayList<GameEntity>();
games.add(game1);
games.add(game2);
user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123"));
order1 = orderService.create(user1.getId(), new OrderEntity(user1,games));
removeData();
genre1 = genreService.create(new GenreEntity("Приключения"));
genre2 = genreService.create(new GenreEntity("Симулятор"));
type1 = typeService.create(new TypeEntity("Игра"));
type2 = typeService.create(new TypeEntity("Программа"));
genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1);
genres1.add(genre2);
genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2);
game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1));
game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2));
games = new ArrayList<GameEntity>();
games.add(game1);
games.add(game2);
user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123"));
order1 = orderService.create(user1.getId(), new OrderEntity(user1,games));
orderService.create(user1.getId(), new OrderEntity(user1,games));
}
@AfterEach
void removeData(){
orderService.getAll().forEach(item -> orderService.delete(item.getUser().getId(),item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
gameService.getAll(0,0).forEach(item -> gameService.delete(item.getId()));
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
}
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(2, orderService.getAll(user1.getId()).size());
}
@Test
@Order(2)
void deleteTest(){
orderService.delete(user1.getId(),order1.getId());
Assertions.assertEquals(1, orderService.getAll(user1.getId()).size());
}
}
//зависимости, core->security, user(loadUserByUserName, userrole), core->configuration, дохуя контроллеров юзера core->session

View File

@ -0,0 +1,77 @@
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.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.core.error.NotFoundException;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import jakarta.transaction.Transactional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class TypeServiceTests {
@Autowired
private TypeService typeService;
private TypeEntity type1;
private TypeEntity type2;
@BeforeEach
void createData() {
removeData();
type2 = typeService.create(new TypeEntity("Программа"));
type1 = typeService.create(new TypeEntity("Игра"));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
}
@Test
@Transactional
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
}
@Test
@Order(1)
@Transactional
void createTest(){
final TypeEntity last = typeService.create(new TypeEntity("Игра2"));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(last, typeService.get(3L));
}
@Test
@Order(2)
@Transactional
void updateTest(){
final String test = "TEST";
final TypeEntity newEntity = typeService.update(type1.getId(), new TypeEntity(test));
Assertions.assertEquals(2, typeService.getAll().size());
Assertions.assertEquals(test, newEntity.getName());
}
@Test
@Order(3)
@Transactional
void deleteTest(){
typeService.delete(type1.getId());
Assertions.assertEquals(1, typeService.getAll().size());
final TypeEntity last = typeService.get(type2.getId());
Assertions.assertEquals(6L, last.getId());
}
}

View File

@ -0,0 +1,67 @@
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.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.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity user1;
private UserEntity user2;
@BeforeEach
void createData() {
removeData();
user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123"));
user2 = userService.create(new UserEntity( "login2", "email@gmail.com", "qwerty1234"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(2, userService.getAll().size());
}
@Test
@Order(2)
void updateTest(){
final UserEntity newEntity = userService.update(user2.getId(), new UserEntity("user11", "mail11", "qwerty11"));
Assertions.assertEquals(2, userService.getAll().size());
Assertions.assertEquals(newEntity.getLogin(), "user11");
}
@Test
@Order(3)
void deleteTest(){
userService.delete(user2.getId());
Assertions.assertEquals(1, userService.getAll().size());
final UserEntity last = userService.get(user1.getId());
Assertions.assertEquals(user1.getId(), last.getId());
}
}

View 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