Промежуточное сохранение.

This commit is contained in:
Programmist73 2023-04-09 12:05:55 +04:00
parent e2d99cec86
commit 43cc05427d
11 changed files with 85 additions and 82 deletions

View File

@ -3,29 +3,29 @@ package premium_store.controller.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import premium_store.controller.DTO.ClientDTO; import premium_store.controller.DTO.ClientDTO;
import premium_store.model.Tank; import premium_store.model.Tank;
import premium_store.service.ClientService; import premium_store.service.GameClientService;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/client") @RequestMapping("/client")
public class ClientController { public class GameClientController {
private final ClientService clientService; private final GameClientService gameClientService;
public ClientController(ClientService clientService){ public GameClientController(GameClientService gameClientService){
this.clientService = clientService; this.gameClientService = gameClientService;
} }
//аннотация PathVariable связывает значения id из URL и Long id //аннотация PathVariable связывает значения id из URL и Long id
@GetMapping("/{id}") @GetMapping("/{id}")
public ClientDTO getClient(@PathVariable Long id) { public ClientDTO getClient(@PathVariable Long id) {
return new ClientDTO(clientService.findClient(id)); return new ClientDTO(gameClientService.findClient(id));
} }
//с помощью Java Stream преобразуем набор пришедших данных в объекты StudentDto //с помощью Java Stream преобразуем набор пришедших данных в объекты StudentDto
@GetMapping("/") @GetMapping("/")
public List<ClientDTO> getClients() { public List<ClientDTO> getClients() {
return clientService.findAllClients().stream() return gameClientService.findAllClients().stream()
.map(ClientDTO::new) .map(ClientDTO::new)
.toList(); .toList();
} }
@ -34,7 +34,7 @@ public class ClientController {
public ClientDTO createClient(@RequestParam("nickName") String nickName, public ClientDTO createClient(@RequestParam("nickName") String nickName,
@RequestParam("email") String email, @RequestParam("email") String email,
@RequestParam("balance") Integer balance) { @RequestParam("balance") Integer balance) {
return new ClientDTO(clientService.addClient(nickName, email, balance)); return new ClientDTO(gameClientService.addClient(nickName, email, balance));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@ -43,11 +43,11 @@ public class ClientController {
@RequestParam("email") String email, @RequestParam("email") String email,
@RequestParam("balance") Integer balance, @RequestParam("balance") Integer balance,
@RequestParam("tanks") List<Tank> tanks) { @RequestParam("tanks") List<Tank> tanks) {
return new ClientDTO(clientService.updateClient(id, nickName, email, balance, tanks)); return new ClientDTO(gameClientService.updateClient(id, nickName, email, balance, tanks));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public ClientDTO deleteClient(@PathVariable Long id) { public ClientDTO deleteClient(@PathVariable Long id) {
return new ClientDTO(clientService.deleteClient(id)); return new ClientDTO(gameClientService.deleteClient(id));
} }
} }

View File

@ -2,7 +2,7 @@ package premium_store.controller.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import premium_store.model.TankLevel; import premium_store.model.TankLevel;
import premium_store.service.LevelService; import premium_store.service.TankLevelService;
import java.util.List; import java.util.List;
@ -11,39 +11,39 @@ import java.util.List;
//так же здесь прописываем вызовы методов CRUD в привязке к URL //так же здесь прописываем вызовы методов CRUD в привязке к URL
@RestController @RestController
@RequestMapping("/level") @RequestMapping("/level")
public class LevelController { public class TankLevelController {
private final LevelService levelService; private final TankLevelService tankLevelService;
public LevelController(LevelService levelService){ public TankLevelController(TankLevelService tankLevelService){
this.levelService = levelService; this.tankLevelService = tankLevelService;
} }
//аннотация PathVariable связывает значения id из URL и Long id //аннотация PathVariable связывает значения id из URL и Long id
@GetMapping("/{id}") @GetMapping("/{id}")
public TankLevel getLevel(@PathVariable Long id) { public TankLevel getLevel(@PathVariable Long id) {
return levelService.findLevel(id); return tankLevelService.findLevel(id);
} }
//с помощью Java Stream преобразуем набор пришедших данных в объекты StudentDto //с помощью Java Stream преобразуем набор пришедших данных в объекты StudentDto
@GetMapping("/") @GetMapping("/")
public List<TankLevel> getLevels() { public List<TankLevel> getLevels() {
return levelService.findAllLevels().stream() return tankLevelService.findAllLevels().stream()
.toList(); .toList();
} }
@PostMapping("/") @PostMapping("/")
public TankLevel createLevel(@RequestParam("Level") int level) { public TankLevel createLevel(@RequestParam("Level") int level) {
return levelService.addLevel(level); return tankLevelService.addLevel(level);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public TankLevel updateLevel(@PathVariable Long id, public TankLevel updateLevel(@PathVariable Long id,
@RequestParam("Level") int level) { @RequestParam("Level") int level) {
return levelService.updateLevel(id, level); return tankLevelService.updateLevel(id, level);
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public TankLevel deleteLevel(@PathVariable Long id) { public TankLevel deleteLevel(@PathVariable Long id) {
return levelService.deleteLevel(id); return tankLevelService.deleteLevel(id);
} }
} }

View File

@ -6,6 +6,7 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@Table(name = "GAMECLIENTS")
public class GameClient { public class GameClient {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -1,12 +1,11 @@
package premium_store.model; package premium_store.model;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
@Entity @Entity
@Table(name = "NATIONS")
public class Nation { public class Nation {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -7,6 +7,7 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Entity @Entity
@Table(name = "TANKS")
public class Tank { public class Tank {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@ -15,20 +16,20 @@ public class Tank {
private String name; private String name;
@ManyToOne @ManyToOne
@JoinColumn(name = "nation_id") @JoinColumn(name = "nation")
private Nation nation; private Nation nation;
@ManyToOne @ManyToOne
@JoinColumn(name = "level_id") @JoinColumn(name = "tankLevel")
private TankLevel tankLevel; private TankLevel tankLevel;
private int cost; private int cost;
//реализация двунаправленной связи многие-ко-многим //реализация двунаправленной связи многие-ко-многим
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "tanks_of_clients", @JoinTable(name = "tanks_clients",
joinColumns = @JoinColumn(name = "tank_id"), joinColumns = @JoinColumn(name = "tank_fk"),
inverseJoinColumns = @JoinColumn(name = "client_id")) inverseJoinColumns = @JoinColumn(name = "client_fk"))
private List<GameClient> gameClients; private List<GameClient> gameClients;
public Tank() { public Tank() {

View File

@ -2,8 +2,10 @@ package premium_store.model;
import javax.persistence.*; import javax.persistence.*;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
@Entity @Entity
@Table(name = "TANKLEVELS")
public class TankLevel { public class TankLevel {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -3,5 +3,5 @@ package premium_store.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import premium_store.model.GameClient; import premium_store.model.GameClient;
public interface ClientRepository extends JpaRepository<GameClient, Long> { public interface GameClientRepository extends JpaRepository<GameClient, Long> {
} }

View File

@ -5,5 +5,5 @@ import premium_store.model.TankLevel;
//класс для взаимодействия с БД вместо низкоуровневого EntityManager //класс для взаимодействия с БД вместо низкоуровневого EntityManager
//передаём тип класса и тип id его элементов //передаём тип класса и тип id его элементов
public interface LevelRepository extends JpaRepository<TankLevel, Long> { public interface TankLevelRepository extends JpaRepository<TankLevel, Long> {
} }

View File

@ -4,7 +4,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import premium_store.model.GameClient; import premium_store.model.GameClient;
import premium_store.model.Tank; import premium_store.model.Tank;
import premium_store.repository.ClientRepository; import premium_store.repository.GameClientRepository;
import premium_store.service.exception.ClientNotFoundException; import premium_store.service.exception.ClientNotFoundException;
import premium_store.util.validation.ValidatorUtil; import premium_store.util.validation.ValidatorUtil;
@ -12,12 +12,12 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
public class ClientService { public class GameClientService {
private final ClientRepository clientRepository; private final GameClientRepository gameClientRepository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public ClientService(ClientRepository clientRepository, ValidatorUtil validatorUtil){ public GameClientService(GameClientRepository gameClientRepository, ValidatorUtil validatorUtil){
this.clientRepository = clientRepository; this.gameClientRepository = gameClientRepository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@ -26,19 +26,19 @@ public class ClientService {
final GameClient gameClient = new GameClient(newNickName, newEmail, newBallance); final GameClient gameClient = new GameClient(newNickName, newEmail, newBallance);
validatorUtil.validate(gameClient); validatorUtil.validate(gameClient);
return clientRepository.save(gameClient); return gameClientRepository.save(gameClient);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public GameClient findClient(Long id) { public GameClient findClient(Long id) {
final Optional<GameClient> client = clientRepository.findById(id); final Optional<GameClient> client = gameClientRepository.findById(id);
return client.orElseThrow(() -> new ClientNotFoundException(id)); return client.orElseThrow(() -> new ClientNotFoundException(id));
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<GameClient> findAllClients() { public List<GameClient> findAllClients() {
return clientRepository.findAll(); return gameClientRepository.findAll();
} }
@Transactional @Transactional
@ -50,13 +50,13 @@ public class ClientService {
currentGameClient.setTanks(newTanks); currentGameClient.setTanks(newTanks);
validatorUtil.validate(currentGameClient); validatorUtil.validate(currentGameClient);
return clientRepository.save(currentGameClient); return gameClientRepository.save(currentGameClient);
} }
@Transactional @Transactional
public GameClient deleteClient(Long id) { public GameClient deleteClient(Long id) {
final GameClient currentGameClient = findClient(id); final GameClient currentGameClient = findClient(id);
clientRepository.delete(currentGameClient); gameClientRepository.delete(currentGameClient);
return currentGameClient; return currentGameClient;
} }
@ -64,6 +64,6 @@ public class ClientService {
//прямой sql-запрос на удаление всех записей в таблице //прямой sql-запрос на удаление всех записей в таблице
@Transactional @Transactional
public void deleteAllClients() { public void deleteAllClients() {
clientRepository.deleteAll(); gameClientRepository.deleteAll();
} }
} }

View File

@ -3,7 +3,7 @@ package premium_store.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import premium_store.model.TankLevel; import premium_store.model.TankLevel;
import premium_store.repository.LevelRepository; import premium_store.repository.TankLevelRepository;
import premium_store.service.exception.LevelNotFoundException; import premium_store.service.exception.LevelNotFoundException;
import premium_store.util.validation.ValidatorUtil; import premium_store.util.validation.ValidatorUtil;
@ -12,12 +12,12 @@ import java.util.Optional;
//сервис после удаления EntityManager и добавления нашего репозитория. То есть у него уже все методы работы с полями прописаны за нас? //сервис после удаления EntityManager и добавления нашего репозитория. То есть у него уже все методы работы с полями прописаны за нас?
@Service @Service
public class LevelService { public class TankLevelService {
private final LevelRepository levelRepository; private final TankLevelRepository tankLevelRepository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public LevelService(LevelRepository levelRepository, ValidatorUtil validatorUtil){ public TankLevelService(TankLevelRepository tankLevelRepository, ValidatorUtil validatorUtil){
this.levelRepository = levelRepository; this.tankLevelRepository = tankLevelRepository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@ -26,13 +26,13 @@ public class LevelService {
final TankLevel tankLevel = new TankLevel(newLevel); final TankLevel tankLevel = new TankLevel(newLevel);
validatorUtil.validate(tankLevel); validatorUtil.validate(tankLevel);
return levelRepository.save(tankLevel); return tankLevelRepository.save(tankLevel);
} }
//здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null //здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null
@Transactional(readOnly = true) @Transactional(readOnly = true)
public TankLevel findLevel(Long id) { public TankLevel findLevel(Long id) {
final Optional<TankLevel> level = levelRepository.findById(id); final Optional<TankLevel> level = tankLevelRepository.findById(id);
//благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения //благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения
return level.orElseThrow(() -> new LevelNotFoundException(id)); return level.orElseThrow(() -> new LevelNotFoundException(id));
@ -40,7 +40,7 @@ public class LevelService {
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<TankLevel> findAllLevels() { public List<TankLevel> findAllLevels() {
return levelRepository.findAll(); return tankLevelRepository.findAll();
} }
@Transactional @Transactional
@ -49,19 +49,19 @@ public class LevelService {
currentTankLevel.setLevel(newLevel); currentTankLevel.setLevel(newLevel);
validatorUtil.validate(currentTankLevel); validatorUtil.validate(currentTankLevel);
return levelRepository.save(currentTankLevel); return tankLevelRepository.save(currentTankLevel);
} }
@Transactional @Transactional
public TankLevel deleteLevel(Long id) { public TankLevel deleteLevel(Long id) {
final TankLevel currentTankLevel = findLevel(id); final TankLevel currentTankLevel = findLevel(id);
levelRepository.delete(currentTankLevel); tankLevelRepository.delete(currentTankLevel);
return currentTankLevel; return currentTankLevel;
} }
@Transactional @Transactional
public void deleteAllLevels() { public void deleteAllLevels() {
levelRepository.deleteAll(); tankLevelRepository.deleteAll();
} }
} }

View File

@ -4,8 +4,8 @@ import premium_store.model.GameClient;
import premium_store.model.TankLevel; import premium_store.model.TankLevel;
import premium_store.model.Nation; import premium_store.model.Nation;
import premium_store.model.Tank; import premium_store.model.Tank;
import premium_store.service.ClientService; import premium_store.service.GameClientService;
import premium_store.service.LevelService; import premium_store.service.TankLevelService;
import premium_store.service.NationService; import premium_store.service.NationService;
import premium_store.service.TankService; import premium_store.service.TankService;
@ -27,22 +27,22 @@ class PremiumStoreApplicationTests {
TankService tankService; TankService tankService;
@Autowired @Autowired
ClientService clientService; GameClientService gameClientService;
@Autowired @Autowired
LevelService levelService; TankLevelService tankLevelService;
@Autowired @Autowired
NationService nationService; NationService nationService;
@Test @Test
void testClientRead() { void testClientRead() {
clientService.deleteAllClients(); gameClientService.deleteAllClients();
GameClient gameClient = clientService.addClient("3tankista73", "fff@mail.ru", 3400); GameClient gameClient = gameClientService.addClient("3tankista73", "fff@mail.ru", 3400);
log.info(gameClient.toString()); log.info(gameClient.toString());
GameClient findGameClient = clientService.findClient(gameClient.getId()); GameClient findGameClient = gameClientService.findClient(gameClient.getId());
log.info(findGameClient.toString()); log.info(findGameClient.toString());
Assertions.assertEquals(gameClient, findGameClient); Assertions.assertEquals(gameClient, findGameClient);
@ -63,30 +63,30 @@ class PremiumStoreApplicationTests {
@Test @Test
void testClientReadNotFound() { void testClientReadNotFound() {
clientService.deleteAllClients(); gameClientService.deleteAllClients();
Assertions.assertThrows(ClientNotFoundException.class, () -> clientService.findClient(-1L)); Assertions.assertThrows(ClientNotFoundException.class, () -> gameClientService.findClient(-1L));
} }
@Test @Test
void testLevelRead() { void testLevelRead() {
tankService.deleteAllTanks(); tankService.deleteAllTanks();
levelService.deleteAllLevels(); tankLevelService.deleteAllLevels();
TankLevel tankLevel = levelService.addLevel(8); TankLevel tankLevel = tankLevelService.addLevel(8);
log.info(tankLevel.toString()); log.info(tankLevel.toString());
TankLevel secondTankLevel = levelService.addLevel(9); TankLevel secondTankLevel = tankLevelService.addLevel(9);
log.info(secondTankLevel.toString()); log.info(secondTankLevel.toString());
Assertions.assertEquals(levelService.findAllLevels().size(), 2); Assertions.assertEquals(tankLevelService.findAllLevels().size(), 2);
} }
@Test @Test
void testLevelReadAllEmpty() { void testLevelReadAllEmpty() {
tankService.deleteAllTanks(); tankService.deleteAllTanks();
levelService.deleteAllLevels(); tankLevelService.deleteAllLevels();
List<TankLevel> tankLevels = levelService.findAllLevels(); List<TankLevel> tankLevels = tankLevelService.findAllLevels();
log.info(tankLevels.toString()); log.info(tankLevels.toString());
Assertions.assertEquals(tankLevels.size(), 0); Assertions.assertEquals(tankLevels.size(), 0);
@ -95,10 +95,10 @@ class PremiumStoreApplicationTests {
@Test @Test
void testTankReadAll() { void testTankReadAll() {
tankService.deleteAllTanks(); tankService.deleteAllTanks();
levelService.deleteAllLevels(); tankLevelService.deleteAllLevels();
TankLevel firstTankLevel = levelService.addLevel(8); TankLevel firstTankLevel = tankLevelService.addLevel(8);
TankLevel secondTankLevel = levelService.addLevel(9); TankLevel secondTankLevel = tankLevelService.addLevel(9);
tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000); tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000);
tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000); tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000);
@ -111,28 +111,28 @@ class PremiumStoreApplicationTests {
@Test @Test
void testClientCreate() { void testClientCreate() {
clientService.deleteAllClients(); gameClientService.deleteAllClients();
GameClient firstGameClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000); GameClient firstGameClient = gameClientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
log.info(firstGameClient.toString()); log.info(firstGameClient.toString());
GameClient secondGameClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000); GameClient secondGameClient = gameClientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
log.info(secondGameClient.toString()); log.info(secondGameClient.toString());
Assertions.assertEquals(clientService.findAllClients().size(), 2); Assertions.assertEquals(gameClientService.findAllClients().size(), 2);
} }
@Test @Test
void testUpdateTank(){ void testUpdateTank(){
tankService.deleteAllTanks(); tankService.deleteAllTanks();
levelService.deleteAllLevels(); tankLevelService.deleteAllLevels();
clientService.deleteAllClients(); gameClientService.deleteAllClients();
GameClient firstGameClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000); GameClient firstGameClient = gameClientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
GameClient secondGameClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000); GameClient secondGameClient = gameClientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
TankLevel firstTankLevel = levelService.addLevel(8); TankLevel firstTankLevel = tankLevelService.addLevel(8);
TankLevel secondTankLevel = levelService.addLevel(9); TankLevel secondTankLevel = tankLevelService.addLevel(9);
Tank firstTank = tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000); Tank firstTank = tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000);
Tank secondTank = tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000); Tank secondTank = tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000);