оно запустилось

This commit is contained in:
bekodeg 2024-06-06 19:47:33 +04:00
parent e58d7117cf
commit bcb8bfa8db
33 changed files with 834 additions and 942 deletions

View File

@ -1,13 +1,38 @@
package com.example.demo;
import com.example.demo.services.GameService;
import com.example.demo.services.PlayService;
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.services.CustomerService;
@SpringBootApplication
public class DemoApplication {
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final CustomerService customerService;
private final GameService gameService;
private final PlayService playService;
public DemoApplication(
CustomerService customerService,
GameService gameService,
PlayService playService
) {
this.customerService = customerService;
this.gameService = gameService;
this.playService = playService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.controllers;
import java.util.List;
import com.example.demo.core.config.Constants;
import com.example.demo.dtos.GameDto;
import com.example.demo.dtos.PlayDto;
import com.example.demo.services.GameService;
import com.example.demo.services.PlayService;
import com.example.demo.services.CustomerService;
import com.example.demo.dtos.CustomerDto;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(Constants.API_URL + "/customers")
public class CustomerController {
private final CustomerService customerService;
private final GameService gameService;
public CustomerController(CustomerService customerService, GameService gameService, PlayService playService){
this.customerService = customerService;
this.gameService = gameService;
}
@GetMapping
public List<CustomerDto> getAll()
{
return customerService.getAllCustomers().stream().map(CustomerDto::new).toList();
}
@GetMapping("/{id}")
public CustomerDto get(@PathVariable(name = "id") long id) {
return new CustomerDto(customerService.findCustomer(id));
}
@PostMapping
public CustomerDto create(@RequestBody CustomerDto customer) {
return new CustomerDto(customerService.addCustomer(customer.getName()));
}
@PutMapping("/{id}")
public CustomerDto update(
@PathVariable(name = "id") long id,
@RequestBody CustomerDto customer) {
return new CustomerDto(customerService.updateCustomer(id, customer.getName()));
}
@DeleteMapping("/{id}")
public CustomerDto delete(@PathVariable(name = "id") long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}
@PostMapping("/{id}/games")
public GameDto createGame(@PathVariable(name = "id") long id, @RequestBody GameDto game){
return new GameDto(gameService.addGame(id, game.getName(), game.getDescription()));
}
@GetMapping("/{id}/games")
public List<GameDto> getGames(@PathVariable(name = "id") long id){
return customerService.findCustomer(id).getGames().stream().map(GameDto::new).toList();
}
@GetMapping("/{id}/plays")
public List<PlayDto> getPlays(@PathVariable(name = "id") long id){
return customerService.findCustomer(id).getPlays().stream().map(PlayDto::new).toList();
}
}

View File

@ -0,0 +1,49 @@
package com.example.demo.controllers;
import com.example.demo.core.config.Constants;
import com.example.demo.dtos.GameDto;
import com.example.demo.dtos.PlayDto;
import com.example.demo.services.GameService;
import com.example.demo.services.PlayService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/games")
public class GameController {
private final GameService gameService;
private final PlayService playService;
public GameController(GameService gameService, PlayService playService){
this.gameService = gameService;
this.playService = playService;
}
@GetMapping
public List<GameDto> getAll() {
return gameService.getAllGames().stream().map(GameDto::new).toList();
}
@GetMapping("/{id}")
public GameDto get(@PathVariable(name = "id") long id) {
return new GameDto(gameService.findGame(id));
}
@PutMapping("/{id}")
public GameDto update(@PathVariable(name = "id") long id, @RequestBody GameDto game) {
return new GameDto(gameService.updateGame(id, game.getName(), game.getDescription()));
}
@DeleteMapping("/{id}")
public GameDto delete(@PathVariable(name = "id") long id)
{
return new GameDto(gameService.deleteGame(id));
}
@PostMapping("/{id}/plays")
public PlayDto create(@PathVariable(name = "id") long id, @RequestBody PlayDto play) {
return new PlayDto(playService.addPlay(id, play.getDate(), play.getDescription()));
}
}

View File

@ -0,0 +1,47 @@
package com.example.demo.controllers;
import com.example.demo.core.config.Constants;
import com.example.demo.dtos.PlayDto;
import com.example.demo.services.PlayService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/plays")
public class PlayController {
private final PlayService playService;
public PlayController(PlayService playService){
this.playService = playService;
}
@GetMapping
public List<PlayDto> getAll()
{
return playService.getAllPlays().stream().map(PlayDto::new).toList();
}
@GetMapping("/{id}")
public PlayDto get(@PathVariable(name = "id") long id)
{
return new PlayDto(playService.findPlay(id));
}
@PutMapping("/{id}")
public PlayDto update(@PathVariable(name = "id") long id, @RequestBody PlayDto play) {
return new PlayDto(playService.updatePlay(id, play.getDate(), play.getDescription()));
}
@DeleteMapping("/{id}")
public PlayDto delete(@PathVariable(name = "id") long id)
{
return new PlayDto(playService.deletePlay(id));
}
@PostMapping("/{id}/customers")
public boolean addCustomer(@PathVariable(name = "id") long id, long customerId){
return playService.addCustomer(id, customerId);
}
}

View File

@ -1,13 +0,0 @@
package com.example.demo.core.config;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfig {
@Bean
ModelMapper modelMapper(){
return new ModelMapper();
}
}

View File

@ -6,10 +6,9 @@ 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("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -1,28 +0,0 @@
package com.example.demo.core.model;
import com.example.demo.core.config.Constants;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.SequenceGenerator;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
protected Long id;
protected BaseEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,72 @@
package com.example.demo.dtos;
import com.example.demo.models.Customer;
import jakarta.validation.constraints.*;
import java.util.ArrayList;
import java.util.List;
public class CustomerDto {
private Long id;
@NotNull
@Min(2)
private String name;
private List<GameDto> games;
private List<PlayDto> plays;
public CustomerDto(){
}
public CustomerDto(Customer customer)
{
id = customer.getId();
name = customer.getName();
var existGames = customer.getGames();
if (existGames != null && !existGames.isEmpty()){
games = existGames.stream().map(GameDto::new).toList();
}
else {
games = new ArrayList<>();
}
var existPlays = customer.getPlays();
if (existPlays != null && !existPlays.isEmpty()){
plays = existPlays.stream().map(PlayDto::new).toList();
}
else {
plays = new ArrayList<>();
}
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public List<GameDto> getGames() {
return games;
}
public void setGames(List<GameDto> games){
this.games = games;
}
public List<PlayDto> getPlays(){
return plays;
}
public void setPlays(List<PlayDto> plays){
this.plays = plays;
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -0,0 +1,74 @@
package com.example.demo.dtos;
import com.example.demo.models.Game;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public class GameDto {
private Long id;
@NotNull
@Min(2)
private String name;
private String description;
private CustomerDto customer;
private List<PlayDto> plays;
public GameDto(){
}
public GameDto(Game game){
name = game.getName();
description = game.getDescription();
var customerExist = game.getCustomer();
if (customerExist != null){
customer = new CustomerDto(customerExist);
}
var playsExist = game.getPlays();
if (playsExist != null && !playsExist.isEmpty()){
plays = playsExist.stream().map(PlayDto::new).toList();
}
}
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 CustomerDto getCustomer(){
return customer;
}
public void setCustomer(CustomerDto customer){
this.customer = customer;
}
public List<PlayDto> getPlays(){
return plays;
}
public void setPlays(List<PlayDto> plays){
this.plays = plays;
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -1,5 +1,6 @@
package com.example.demo.plays.api;
package com.example.demo.dtos;
import com.example.demo.models.Play;
import jakarta.validation.constraints.NotNull;
import java.util.Date;
@ -14,9 +15,26 @@ public class PlayDto {
private Date date;
@NotNull
private Long game;
private GameDto game;
private List<Long> users;
private List<CustomerDto> customers;
public PlayDto(){
}
public PlayDto(Play play){
description = play.getDescription();
date = play.getDate();
var existGame = play.getGame();
if (existGame != null){
game = new GameDto(existGame);
}
else {
game = null;
}
}
public String getDescription(){
return description;
@ -32,18 +50,18 @@ public class PlayDto {
this.date = date;
}
public Long getGame(){
public GameDto getGame(){
return game;
}
public void setGame(Long game){
public void setGame(GameDto game){
this.game = game;
}
public List<Long> getUsers(){
return users;
public List<CustomerDto> getCustomers(){
return customers;
}
public void setUsers(List<Long> users){
this.users = users;
public void setCustomers(List<CustomerDto> customers){
this.customers = customers;
}
public Long getId(){

View File

@ -1,61 +0,0 @@
package com.example.demo.games.api;
import com.example.demo.core.config.Constants;
import com.example.demo.games.service.GameService;
import com.example.demo.games.model.GameEntity;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "game")
public class GameController {
private final GameService gameService;
private final ModelMapper modelMapper;
public GameController(GameService gameService, ModelMapper modelMapper){
this.gameService = gameService;
this.modelMapper = modelMapper;
}
private GameDto toDto(GameEntity entity){
return modelMapper.map(entity, GameDto.class);
}
private GameEntity toEntity(GameDto dto){
return modelMapper.map(dto, GameEntity.class);
}
@GetMapping
public List<GameDto> getAll() {
return gameService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/user/{userId}")
public List<GameDto> getByUser(@PathVariable Long userId) {
return gameService.getByUser(userId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public GameDto get(@PathVariable(name = "id") long id) {
return toDto(gameService.get(id));
}
@PostMapping
public GameDto create(@RequestBody @Valid GameDto dto, @RequestParam Long userId) {
return toDto(gameService.create(userId, 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

@ -1,54 +0,0 @@
package com.example.demo.games.api;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public class GameDto {
private Long id;
@NotNull
@Min(2)
private String name;
private String description;
private Long user;
private List<Long> plays;
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 Long getUser(){
return user;
}
public void setUser(Long user){
this.user = user;
}
public List<Long> getPlays(){
return plays;
}
public void setPlays(List<Long> plays){
this.plays = plays;
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -1,61 +0,0 @@
package com.example.demo.games.model;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.plays.model.PlayEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.*;
import java.util.List;
@Entity
@Table(name = "game")
public class GameEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 100)
private String name;
@Column(length = 500)
private String description;
@ManyToOne
@JoinColumn(name = "userId")
private UserEntity user;
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("date desc")
List<PlayEntity> plays;
public GameEntity() {
}
public GameEntity(String name) {
this.name = name;
}
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 UserEntity getUser(){
return user;
}
public void setUser(UserEntity user){
this.user = user;
}
public List<PlayEntity> getPlays(){
return plays;
}
public void setPlays(List<PlayEntity> plays){
this.plays = plays;
}
}

View File

@ -1,9 +0,0 @@
package com.example.demo.games.repository;
import com.example.demo.games.model.GameEntity;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface GameRepository extends CrudRepository<GameEntity, Long> {
List<GameEntity> findByUserId(long UserId);
}

View File

@ -1,75 +0,0 @@
package com.example.demo.games.service;
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.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
import com.example.demo.users.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class GameService {
private final GameRepository repository;
private final UserService userService;
public GameService(
GameRepository repository,
UserService userService){
this.repository = repository;
this.userService = userService;
}
@Transactional(readOnly = true)
public List<GameEntity> getAll()
{
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public List<GameEntity> getByUser(long userId)
{
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public GameEntity get(long id){
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public GameEntity create(long userId, GameEntity 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 GameEntity update(long id, GameEntity entity){
final GameEntity existEntity = get(id);
existEntity.setName(entity.getName());
existEntity.setDescription(entity.getDescription());
existEntity.setUser(entity.getUser());
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,74 @@
package com.example.demo.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(unique = true, length = 50)
private String name;
@OneToMany(mappedBy = "customer", cascade=CascadeType.REMOVE)
@OrderBy("name ASC")
private List<Game> games = new ArrayList<>();
@ManyToMany
@OrderBy("date desc")
private List<Play> plays = new ArrayList<>();
public Customer() {
}
public Customer(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer cart = (Customer) o;
return Objects.equals(name, cart.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
public long getId(){
return id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public List<Game> getGames(){
return games;
}
public void setGames(List<Game> games){
this.games = games;
}
public List<Play> getPlays(){
return plays;
}
public void setPlays(List<Play> plays){
this.plays = plays;
}
public boolean addPlay(Play play){
return plays.add(play);
}
}

View File

@ -0,0 +1,88 @@
package com.example.demo.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long customerId;
@Column(length = 50)
private String name;
@Column(length = 500)
private String description;
@ManyToOne
@JoinColumn(name = "сustomerId", updatable = false, insertable = false)
private Customer customer;
@OneToMany(mappedBy = "game", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("date desc")
Set<Play> plays = new HashSet<>();
public Game() {
}
public Game(String name, String description, Customer customer) {
this.name = name;
this.customer = customer;
this.customerId = customer.getId();
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Game game = (Game) o;
return Objects.equals(customerId, game.customerId) && Objects.equals(name, game.name);
}
@Override
public int hashCode() {
return Objects.hash(customerId, name);
}
public long getId() {
return id;
}
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 Customer getCustomer(){
return customer;
}
public void setCustomer(Customer customer){
this.customer = customer;
this.customerId = customer.getId();
}
public long getCustomerId() {
return customerId;
}
public Set<Play> getPlays(){
return plays;
}
public void setPlays(Set<Play> plays){
this.plays = plays;
}
}

View File

@ -0,0 +1,88 @@
package com.example.demo.models;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
public class Play {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long gameId;
@Column(length = 500)
private String description;
@Column(nullable = false)
private Date date;
@ManyToOne()
@JoinColumn(name = "gameId", updatable = false, insertable = false)
private Game game;
@ManyToMany()
@OrderBy("name asc")
private List<Customer> customers = new ArrayList<>();
public Play() {
}
public Play(Game game, Date date, String description){
this.description = description;
this.date = date;
this.game = game;
this.gameId = game.getId();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Play cart = (Play) o;
return Objects.equals(gameId, cart.gameId) && Objects.equals(date, cart.date);
}
@Override
public int hashCode() {
return Objects.hash(gameId, date);
}
public long getId() {
return id;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getDate(){
return date;
}
public void setDate(Date date){
this.date = date;
}
public Game getGame(){
return game;
}
public void setGame(Game game){
this.game = game;
this.gameId = game.getId();
}
public List<Customer> getCustomers(){
return customers;
}
public void setCustomers(List<Customer> customers){
this.customers = customers;
}
}

View File

@ -1,63 +0,0 @@
package com.example.demo.plays.api;
import com.example.demo.core.config.Constants;
import com.example.demo.games.api.GameDto;
import com.example.demo.games.model.GameEntity;
import com.example.demo.plays.model.PlayEntity;
import com.example.demo.plays.service.PlayService;
import com.example.demo.users.api.UserDto;
import com.example.demo.users.model.UserEntity;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/tables")
public class PlayController {
private final PlayService playService;
private final ModelMapper modelMapper;
public PlayController(PlayService playService, ModelMapper modelMapper){
this.playService = playService;
this.modelMapper = modelMapper;
}
private PlayDto toDto(PlayEntity entity) {
return modelMapper.map(entity, PlayDto.class);
}
private PlayEntity toEntity(PlayDto dto){
return modelMapper.map(dto, PlayEntity.class);
}
@GetMapping
public List<PlayDto> getAll()
{
return playService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public PlayDto get(@PathVariable(name = "id") long id)
{
return toDto(playService.get(id));
}
@PostMapping("/")
public PlayDto create(@RequestBody @Valid PlayDto dto) {
return toDto(playService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public PlayDto update(@PathVariable(name = "id") long id, @RequestBody PlayDto dto) {
return toDto(playService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public PlayDto delete(@PathVariable(name = "id") long id)
{
return toDto(playService.delete(id));
}
}

View File

@ -1,62 +0,0 @@
package com.example.demo.plays.model;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.games.model.GameEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.*;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "play")
public class PlayEntity extends BaseEntity {
@Column(length = 500)
private String description;
@Column(nullable = false)
private Date date;
@ManyToOne
@JoinColumn(name = "gameId")
private GameEntity game;
@ManyToMany
private Set<UserEntity> users;
public PlayEntity() {
}
public PlayEntity(Date date, String description){
this.description = description;
this.date = date;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getDate(){
return date;
}
public void setDate(Date date){
this.date = date;
}
public GameEntity getGame(){
return game;
}
public void setGame(GameEntity game){
this.game = game;
}
public Set<UserEntity> getUsers(){
return users;
}
public void setUsers(Set<UserEntity> gamers){
this.users = gamers;
}
}

View File

@ -1,13 +0,0 @@
package com.example.demo.plays.repository;
import com.example.demo.plays.model.PlayEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface PlayRepository extends CrudRepository<PlayEntity, Long> {
List<PlayEntity> findByUserId(long userId);
List<PlayEntity> findByGameId(long gameId);
}

View File

@ -1,92 +0,0 @@
package com.example.demo.plays.service;
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.plays.model.PlayEntity;
import com.example.demo.plays.repository.PlayRepository;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.persistence.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.StreamSupport;
@Service
public class PlayService {
private final PlayRepository repository;
private final UserService userService;
private final GameService gameService;
public PlayService(PlayRepository repository, UserService userService, GameService gameService)
{
this.repository = repository;
this.userService = userService;
this.gameService = gameService;
}
@Transactional(readOnly = true)
public List<PlayEntity> getAll(){
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public List<PlayEntity> getByUserId(long userId){
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public List<PlayEntity> getByGameId(long gameId){
return repository.findByGameId(gameId);
}
@Transactional
public PlayEntity get(Long id){
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public PlayEntity create(PlayEntity entity){
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final GameEntity existGame = gameService.get(entity.getGame().getId());
entity.setGame(existGame);
Set<UserEntity> users = new HashSet<UserEntity>() {
};
entity.getUsers().forEach(user -> {
final UserEntity existUser = userService.get(user.getId());
users.add(existUser);
});
entity.setUsers(users);
return repository.save(entity);
}
@Transactional
public PlayEntity update(Long id, PlayEntity entity){
final PlayEntity existEntity = get(id);
existEntity.setDescription(entity.getDescription());
existEntity.setDate(entity.getDate());
existEntity.setGame(entity.getGame());
existEntity.setUsers(entity.getUsers());
return repository.save(existEntity);
}
@Transactional
public PlayEntity delete(Long id){
final PlayEntity existEntity = get(id);
repository.delete(existEntity);
return existEntity;
}
}

View File

@ -0,0 +1,56 @@
package com.example.demo.services;
import com.example.demo.models.Customer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
@Transactional
public Customer addCustomer(String name) {
if(!StringUtils.hasText(name)){
throw new IllegalArgumentException("Empty name");
}
final Customer customer = new Customer(name);
em.persist(customer);
return customer;
}
@Transactional
public Customer findCustomer(Long id){
final Customer customer = em.find(Customer.class, id);
if (customer == null){
throw new EntityNotFoundException(String.format("customer with id [%s] is not found", id));
}
return customer;
}
@Transactional
public List<Customer> getAllCustomers(){
return em.createQuery("SELECT u FROM Customer u", Customer.class).getResultList();
}
@Transactional
public Customer updateCustomer(Long id, String name){
final Customer currentCustomer = findCustomer(id);
if(StringUtils.hasText(name))
currentCustomer.setName(name);
return currentCustomer;
}
@Transactional
public Customer deleteCustomer(Long id){
final Customer currentCustomer = findCustomer(id);
em.remove(currentCustomer);
return currentCustomer;
}
}

View File

@ -0,0 +1,69 @@
package com.example.demo.services;
import com.example.demo.models.Game;
import com.example.demo.models.Customer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class GameService {
@PersistenceContext
private EntityManager em;
private final CustomerService customerService;
public GameService(CustomerService customerService){
this.customerService = customerService;
}
@Transactional
public Game addGame(Long customerId, String name, String description){
if(!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Empty name");
}
final Customer customer = customerService.findCustomer(customerId);
if (customer == null){
throw new IllegalArgumentException("customerId invalid");
}
final Game Game = new Game(name, description, customer);
em.persist(Game);
return Game;
}
@Transactional
public Game findGame(Long id){
final Game Game = em.find(Game.class, id);
if(Game==null){
throw new EntityNotFoundException(String.format("Game with id [%s] is not found", id));
}
return Game;
}
@Transactional
public List<Game> getAllGames(){
return em.createQuery("SELECT g FROM Game g", Game.class).getResultList();
}
@Transactional
public Game updateGame(Long id, String name, String description){
final Game currentGame = findGame(id);
if(StringUtils.hasText(name))
currentGame.setName(name);
if(StringUtils.hasText(description))
currentGame.setDescription(description);
return currentGame;
}
@Transactional
public Game deleteGame(Long id){
final Game currentGame = findGame(id);
em.remove(currentGame);
return currentGame;
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo.services;
import com.example.demo.models.Game;
import com.example.demo.models.Play;
import com.example.demo.models.Customer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
@Service
public class PlayService {
@PersistenceContext
private EntityManager em;
private final GameService gameService;
private final CustomerService customerService;
public PlayService(GameService gameService, CustomerService customerService){
this.gameService = gameService;
this.customerService = customerService;
}
@Transactional
public Play addPlay(Long gameId, Date date, String description){
final Game game = gameService.findGame(gameId);
if (game == null){
throw new IllegalArgumentException("gameId invalid");
}
final Play Play = new Play(game, date, description);
em.persist(Play);
return Play;
}
@Transactional
public Play findPlay(Long id){
final Play Play = em.find(Play.class, id);
if (Play == null){
throw new EntityNotFoundException(String.format("Play with id [%s] is not found", id));
}
return Play;
}
@Transactional
public List<Play> getAllPlays(){
return em.createQuery("SELECT p FROM Play p", Play.class).getResultList();
}
@Transactional
public Play updatePlay(Long id, Date date, String description){
final Play currentPlay = findPlay(id);
if(StringUtils.hasText(description))
currentPlay.setDescription(description);
if(date != null)
currentPlay.setDate(date);
return currentPlay;
}
@Transactional
public Play deletePlay(Long id){
final Play currentPlay = findPlay(id);
em.remove(currentPlay);
return currentPlay;
}
@Transactional
public boolean addCustomer(Long id, Long customerId){
final Play currentPlay = findPlay(id);
final Customer customer = customerService.findCustomer(customerId);
return customer.addPlay(currentPlay);
}
}

View File

@ -1,61 +0,0 @@
package com.example.demo.users.api;
import java.util.List;
import com.example.demo.core.config.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(Constants.API_URL + "/users")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper){
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public List<UserDto> getAll()
{
return userService.getAll()
.stream()
.map(this::toDto)
.toList();
}
@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

@ -1,57 +0,0 @@
package com.example.demo.users.api;
import jakarta.validation.constraints.*;
import java.util.List;
public class UserDto {
private Long id;
@NotNull
@Min(2)
private String name;
@NotBlank
@Min(4)
private String login;
private List<Long> games;
private List<Long> plays;
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public String getLogin()
{
return login;
}
public void setLogin(String login){
this.login = login;
}
public List<Long> getGames() {
return games;
}
public void setGames(List<Long> games){
this.games = games;
}
public List<Long> getPlays(){
return plays;
}
public void setPlays(List<Long> plays){
this.plays = plays;
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -1,62 +0,0 @@
package com.example.demo.users.model;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.games.model.GameEntity;
import com.example.demo.plays.model.PlayEntity;
import jakarta.persistence.*;
import java.util.List;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 100)
private String name;
@Column(nullable = false, unique = true, length = 50)
private String login;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("name asc")
private List<GameEntity> games;
@ManyToMany(mappedBy = "usersPlays")
@OrderBy("date desc")
private List<PlayEntity> plays;
public UserEntity() {
}
public UserEntity(String login, String name) {
this.login = login;
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login){
this.login = login;
}
public List<GameEntity> getGames(){
return games;
}
public void setGames(List<GameEntity> games){
this.games = games;
}
public List<PlayEntity> getPlays(){
return plays;
}
public void setPlays(List<PlayEntity> plays){
this.plays = plays;
}
}

View File

@ -1,12 +0,0 @@
package com.example.demo.users.repository;
import com.example.demo.users.model.UserEntity;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
Optional<UserEntity> findByGameId(long gameId);
}

View File

@ -1,74 +0,0 @@
package com.example.demo.users.service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.repository.GameRepository;
import com.example.demo.games.service.GameService;
import com.example.demo.plays.repository.PlayRepository;
import com.example.demo.plays.service.PlayService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class UserService {
private final UserRepository repository;
public UserService(
UserRepository repository,
GameService gameService,
PlayService playService
){
this.repository = repository;
}
private void checkLogin(String login) {
if (repository.findByLoginIgnoreCase(login).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(
repository.findAll().spliterator(), false).toList();
}
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");
}
checkLogin(entity.getLogin());
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
checkLogin(entity.getLogin());
existsEntity.setLogin(entity.getLogin());
existsEntity.setName(entity.getName());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1 +1,11 @@
spring.application.name=demo
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=123
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -1,65 +0,0 @@
package com.example.demo.DemoApplicationTests;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Objects;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class GameServiceTest {
@Autowired
private GameService gameService;
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(0, gameService.getAll().size());
gameService.create(new GameEntity(null, "Древний ужас"));
Assertions.assertEquals(1, gameService.getAll().size());
gameService.create(new GameEntity(null, "Покорение марса"));
Assertions.assertEquals(2, gameService.getAll().size());
}
@Test
@Order(2)
void UpdateTest(){
var newEntity = new GameEntity(1L, "Аркхем");
Assertions.assertNotEquals(newEntity, gameService.get(1L));
final GameEntity newEntityCopy = gameService.update(1L, newEntity);
AssertionsEqualEntity(newEntityCopy, newEntity);
Assertions.assertEquals(2, gameService.getAll().size());
AssertionsEqualEntity(newEntity, gameService.get(1L));
}
@Test
@Order(3)
void DeleteTest(){
Assertions.assertThrows(NullPointerException.class, () -> gameService.delete(3L));
Assertions.assertEquals(2L, gameService.getAll().size());
gameService.delete(1L);
Assertions.assertEquals(1L, gameService.getAll().size());
final GameEntity last = gameService.get(2L);
Assertions.assertEquals(2L, last.getId());
final GameEntity newEntity = gameService.create(new GameEntity(null, "Крылья"));
Assertions.assertEquals(2L, gameService.getAll().size());
Assertions.assertEquals(3L, newEntity.getId());
}
private void AssertionsEqualEntity(GameEntity l, GameEntity r){
Assertions.assertEquals(l.getName(), r.getName());
Assertions.assertEquals(l.getId(), r.getId());
}
}

View File

@ -1,64 +0,0 @@
package com.example.demo.DemoApplicationTests;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Objects;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserServiceTest {
private boolean equalEntity(UserEntity l, UserEntity r){
return l.getId() == r.getId() &&
Objects.equals(l.getName(), r.getName()) &&
Objects.equals(l.getLogin(), r.getLogin()) &&
Objects.equals(l.getPassword(), r.getPassword());
}
@Autowired
private UserService userService;
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
@Order(1)
void createTest(){
Assertions.assertEquals(0, userService.getAll().size());
userService.create(new UserEntity(null, "cawa", "cacawa", "1111"));
Assertions.assertEquals(1, userService.getAll().size());
userService.create(new UserEntity(null, "lambada", "lam", "0000"));
Assertions.assertEquals(2, userService.getAll().size());
}
@Test
@Order(2)
void UpdateTest(){
var newEntity = new UserEntity(1L, "name", "login", "password");
Assertions.assertNotEquals(newEntity, userService.get(1L));
final UserEntity newEntityCopy = userService.update(
1L, newEntity);
Assertions.assertTrue(equalEntity(newEntityCopy, newEntity));
Assertions.assertEquals(2L, userService.getAll().size());
Assertions.assertTrue(equalEntity(newEntity, userService.get(1L)));
}
@Test
@Order(3)
void DeleteTest(){
Assertions.assertThrows(NullPointerException.class, () -> userService.delete(3L));
Assertions.assertEquals(2L, userService.getAll().size());
userService.delete(1L);
Assertions.assertEquals(1L, userService.getAll().size());
final UserEntity last = userService.get(2L);
Assertions.assertEquals(2L, last.getId());
final UserEntity newEntity = userService.create(new UserEntity(null, "1", "1", "1"));
Assertions.assertEquals(2L, userService.getAll().size());
Assertions.assertEquals(3L, newEntity.getId());
}
}