Переименование сущностей и корректировка тестов.

This commit is contained in:
Programmist73 2023-04-09 11:13:33 +04:00
parent 8ecf9e9cab
commit e2d99cec86
14 changed files with 140 additions and 144 deletions

View File

@ -1,6 +1,6 @@
package premium_store.controller.DTO;
import premium_store.model.Client;
import premium_store.model.GameClient;
import premium_store.model.Tank;
import java.util.List;
@ -10,9 +10,9 @@ public class ClientDTO {
private final long id;
private final List<Tank> tanks;
public ClientDTO(Client client){
this.id = client.getId();
this.tanks = client.getTanks();
public ClientDTO(GameClient gameClient){
this.id = gameClient.getId();
this.tanks = gameClient.getTanks();
}
public long getId(){

View File

@ -1,24 +1,24 @@
package premium_store.controller.DTO;
import premium_store.model.Client;
import premium_store.model.GameClient;
import premium_store.model.Tank;
import java.util.List;
public class TankDTO {
private final long id;
private final List<Client> clients;
private final List<GameClient> gameClients;
public TankDTO(Tank tank){
this.id = tank.getId();
this.clients = tank.getClients();
this.gameClients = tank.getClients();
}
public long getId(){
return id;
}
public List<Client> getClients(){
return clients;
public List<GameClient> getClients(){
return gameClients;
}
}

View File

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

View File

@ -2,8 +2,8 @@ package premium_store.controller.controller;
import org.springframework.web.bind.annotation.*;
import premium_store.controller.DTO.TankDTO;
import premium_store.model.Client;
import premium_store.model.Level;
import premium_store.model.GameClient;
import premium_store.model.TankLevel;
import premium_store.model.Nation;
import premium_store.service.TankService;
@ -35,19 +35,19 @@ public class TankController {
@PostMapping("/")
public TankDTO createTank(@RequestParam("firstName") String name,
@RequestParam("nation") Nation nation,
@RequestParam("level") Level level,
@RequestParam("level") TankLevel tankLevel,
@RequestParam("cost") int cost) {
return new TankDTO(tankService.addTank(name, nation, level, cost));
return new TankDTO(tankService.addTank(name, nation, tankLevel, cost));
}
@PutMapping("/{id}")
public TankDTO updateTank(@PathVariable Long id,
@RequestParam("firstName") String name,
@RequestParam("nation") Nation nation,
@RequestParam("level") Level level,
@RequestParam("level") TankLevel tankLevel,
@RequestParam("cost") int cost,
@RequestParam("clients")List<Client> clients) {
return new TankDTO(tankService.updateTank(id, name, nation, level, cost, clients));
@RequestParam("clients")List<GameClient> gameClients) {
return new TankDTO(tankService.updateTank(id, name, nation, tankLevel, cost, gameClients));
}
@DeleteMapping("/{id}")

View File

@ -6,7 +6,7 @@ import java.util.List;
import java.util.Objects;
@Entity
public class Client {
public class GameClient {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ -19,12 +19,12 @@ public class Client {
private Integer balance;
@ManyToMany(mappedBy = "clients", fetch= FetchType.EAGER)
@ManyToMany(mappedBy = "gameClients", fetch= FetchType.EAGER)
private List<Tank> tanks;
public Client(){ }
public GameClient(){ }
public Client(String nickName, String email, Integer balance){
public GameClient(String nickName, String email, Integer balance){
this.nickName = nickName;
this.email = email;
this.balance = balance;
@ -76,9 +76,9 @@ public class Client {
if (o == null || getClass() != o.getClass())
return false;
Client client = (Client) o;
GameClient gameClient = (GameClient) o;
return Objects.equals(id, client.id);
return Objects.equals(id, gameClient.id);
}
@Override

View File

@ -1,6 +1,5 @@
package premium_store.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@ -13,7 +12,6 @@ public class Nation {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String nation;
public Nation() {

View File

@ -12,7 +12,6 @@ public class Tank {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@ManyToOne
@ -21,27 +20,26 @@ public class Tank {
@ManyToOne
@JoinColumn(name = "level_id")
private Level level;
private TankLevel tankLevel;
@Column(nullable = false)
private int cost;
//реализация двунаправленной связи мнокие-ко-многим
//реализация двунаправленной связи многие-ко-многим
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(name = "tanks_of_clients",
joinColumns = @JoinColumn(name = "tank_id"),
inverseJoinColumns = @JoinColumn(name = "client_id"))
private List<Client> clients;
private List<GameClient> gameClients;
public Tank() {
}
public Tank(String name, Nation nation, Level level, int cost) {
public Tank(String name, Nation nation, TankLevel tankLevel, int cost) {
this.name = name;
this.nation = nation;
this.level = level;
this.tankLevel = tankLevel;
this.cost = cost;
clients = new ArrayList<>();
gameClients = new ArrayList<>();
}
public Long getId(){
@ -64,12 +62,12 @@ public class Tank {
this.cost = cost;
}
public Level getLevel() {
return level;
public TankLevel getLevel() {
return tankLevel;
}
public void setLevel(Level level) {
this.level = level;
public void setLevel(TankLevel tankLevel) {
this.tankLevel = tankLevel;
}
public Nation getNation() {
@ -80,26 +78,26 @@ public class Tank {
this.nation = nation;
}
public List<Client> getClients() {
return clients;
public List<GameClient> getClients() {
return gameClients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
public void setClients(List<GameClient> gameClients) {
this.gameClients = gameClients;
}
public void addClient(Client newClient){
if (clients == null){
this.clients = new ArrayList<>();
public void addClient(GameClient newGameClient){
if (gameClients == null){
this.gameClients = new ArrayList<>();
}
if (!clients.contains(newClient))
this.clients.add(newClient);
if (!gameClients.contains(newGameClient))
this.gameClients.add(newGameClient);
}
public void removeClient(Client remClient){
if (clients.contains(remClient))
this.clients.remove(remClient);
public void removeClient(GameClient remGameClient){
if (gameClients.contains(remGameClient))
this.gameClients.remove(remGameClient);
}
@Override
@ -125,9 +123,9 @@ public class Tank {
"id=" + id +
", name='" + name + '\'' +
", nation='" + nation + '\'' +
", level='" + level + '\'' +
", level='" + tankLevel + '\'' +
", cost='" + cost + '\'' +
", clients='" + clients.stream().map(Object::toString).collect(Collectors.joining(", ")) + '\'' +
", clients='" + gameClients.stream().map(Object::toString).collect(Collectors.joining(", ")) + '\'' +
'}';
}
}

View File

@ -4,7 +4,7 @@ import javax.persistence.*;
import java.util.Objects;
@Entity
public class Level {
public class TankLevel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ -12,10 +12,10 @@ public class Level {
@Column(nullable = false)
private int level;
public Level() {
public TankLevel() {
}
public Level(int level) {
public TankLevel(int level) {
this.level = level;
}
@ -42,9 +42,9 @@ public class Level {
if (o == null || getClass() != o.getClass())
return false;
Level level = (Level) o;
TankLevel tankLevel = (TankLevel) o;
return Objects.equals(id, level.id);
return Objects.equals(id, tankLevel.id);
}
@Override

View File

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

View File

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

View File

@ -2,7 +2,7 @@ package premium_store.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import premium_store.model.Client;
import premium_store.model.GameClient;
import premium_store.model.Tank;
import premium_store.repository.ClientRepository;
import premium_store.service.exception.ClientNotFoundException;
@ -22,43 +22,43 @@ public class ClientService {
}
@Transactional
public Client addClient(String newNickName, String newEmail, Integer newBallance) {
final Client client = new Client(newNickName, newEmail, newBallance);
validatorUtil.validate(client);
public GameClient addClient(String newNickName, String newEmail, Integer newBallance) {
final GameClient gameClient = new GameClient(newNickName, newEmail, newBallance);
validatorUtil.validate(gameClient);
return clientRepository.save(client);
return clientRepository.save(gameClient);
}
@Transactional(readOnly = true)
public Client findClient(Long id) {
final Optional<Client> client = clientRepository.findById(id);
public GameClient findClient(Long id) {
final Optional<GameClient> client = clientRepository.findById(id);
return client.orElseThrow(() -> new ClientNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Client> findAllClients() {
public List<GameClient> findAllClients() {
return clientRepository.findAll();
}
@Transactional
public Client updateClient(Long id, String newNickName, String newEmail, Integer newBalance, List<Tank> newTanks) {
final Client currentClient = findClient(id);
currentClient.setNickName(newNickName);
currentClient.setEmail(newEmail);
currentClient.setBalance(newBalance);
currentClient.setTanks(newTanks);
validatorUtil.validate(currentClient);
public GameClient updateClient(Long id, String newNickName, String newEmail, Integer newBalance, List<Tank> newTanks) {
final GameClient currentGameClient = findClient(id);
currentGameClient.setNickName(newNickName);
currentGameClient.setEmail(newEmail);
currentGameClient.setBalance(newBalance);
currentGameClient.setTanks(newTanks);
validatorUtil.validate(currentGameClient);
return clientRepository.save(currentClient);
return clientRepository.save(currentGameClient);
}
@Transactional
public Client deleteClient(Long id) {
final Client currentClient = findClient(id);
clientRepository.delete(currentClient);
public GameClient deleteClient(Long id) {
final GameClient currentGameClient = findClient(id);
clientRepository.delete(currentGameClient);
return currentClient;
return currentGameClient;
}
//прямой sql-запрос на удаление всех записей в таблице

View File

@ -2,7 +2,7 @@ package premium_store.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import premium_store.model.Level;
import premium_store.model.TankLevel;
import premium_store.repository.LevelRepository;
import premium_store.service.exception.LevelNotFoundException;
import premium_store.util.validation.ValidatorUtil;
@ -22,42 +22,42 @@ public class LevelService {
}
@Transactional
public Level addLevel(int newLevel) {
final Level level = new Level(newLevel);
validatorUtil.validate(level);
public TankLevel addLevel(int newLevel) {
final TankLevel tankLevel = new TankLevel(newLevel);
validatorUtil.validate(tankLevel);
return levelRepository.save(level);
return levelRepository.save(tankLevel);
}
//здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null
@Transactional(readOnly = true)
public Level findLevel(Long id) {
final Optional<Level> level = levelRepository.findById(id);
public TankLevel findLevel(Long id) {
final Optional<TankLevel> level = levelRepository.findById(id);
//благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения
return level.orElseThrow(() -> new LevelNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Level> findAllLevels() {
public List<TankLevel> findAllLevels() {
return levelRepository.findAll();
}
@Transactional
public Level updateLevel(Long id, int newLevel) {
final Level currentLevel = findLevel(id);
currentLevel.setLevel(newLevel);
validatorUtil.validate(currentLevel);
public TankLevel updateLevel(Long id, int newLevel) {
final TankLevel currentTankLevel = findLevel(id);
currentTankLevel.setLevel(newLevel);
validatorUtil.validate(currentTankLevel);
return levelRepository.save(currentLevel);
return levelRepository.save(currentTankLevel);
}
@Transactional
public Level deleteLevel(Long id) {
final Level currentLevel = findLevel(id);
levelRepository.delete(currentLevel);
public TankLevel deleteLevel(Long id) {
final TankLevel currentTankLevel = findLevel(id);
levelRepository.delete(currentTankLevel);
return currentLevel;
return currentTankLevel;
}
@Transactional

View File

@ -2,8 +2,8 @@ package premium_store.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import premium_store.model.Client;
import premium_store.model.Level;
import premium_store.model.GameClient;
import premium_store.model.TankLevel;
import premium_store.model.Nation;
import premium_store.model.Tank;
import premium_store.repository.TankRepository;
@ -24,8 +24,8 @@ public class TankService {
}
@Transactional
public Tank addTank(String newName, Nation newNation, Level newLevel, int newCost) {
final Tank tank = new Tank(newName, newNation, newLevel, newCost);
public Tank addTank(String newName, Nation newNation, TankLevel newTankLevel, int newCost) {
final Tank tank = new Tank(newName, newNation, newTankLevel, newCost);
validatorUtil.validate(tank);
return tankRepository.save(tank);
@ -45,13 +45,13 @@ public class TankService {
@Transactional
public Tank updateTank(Long id, String newName, Nation newNation,
Level newLevel, int newCost, List<Client> newClients) {
TankLevel newTankLevel, int newCost, List<GameClient> newGameClients) {
final Tank currentTank = findTank(id);
currentTank.setName(newName);
currentTank.setNation(newNation);
currentTank.setLevel(newLevel);
currentTank.setLevel(newTankLevel);
currentTank.setCost(newCost);
currentTank.setClients(newClients);
currentTank.setClients(newGameClients);
validatorUtil.validate(currentTank);
return tankRepository.save(currentTank);

View File

@ -1,7 +1,7 @@
package premium_store;
import premium_store.model.Client;
import premium_store.model.Level;
import premium_store.model.GameClient;
import premium_store.model.TankLevel;
import premium_store.model.Nation;
import premium_store.model.Tank;
import premium_store.service.ClientService;
@ -15,8 +15,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import premium_store.service.exception.ClientNotFoundException;
import javax.persistence.EntityNotFoundException;
import java.util.*;
@SpringBootTest
@ -39,13 +39,13 @@ class PremiumStoreApplicationTests {
void testClientRead() {
clientService.deleteAllClients();
Client client = clientService.addClient("3tankista73", "fff@mail.ru", 3400);
log.info(client.toString());
GameClient gameClient = clientService.addClient("3tankista73", "fff@mail.ru", 3400);
log.info(gameClient.toString());
Client findClient = clientService.findClient(client.getId());
log.info(findClient.toString());
GameClient findGameClient = clientService.findClient(gameClient.getId());
log.info(findGameClient.toString());
Assertions.assertEquals(client, findClient);
Assertions.assertEquals(gameClient, findGameClient);
}
@Test
@ -64,7 +64,7 @@ class PremiumStoreApplicationTests {
@Test
void testClientReadNotFound() {
clientService.deleteAllClients();
Assertions.assertThrows(EntityNotFoundException.class, () -> clientService.findClient(-1L));
Assertions.assertThrows(ClientNotFoundException.class, () -> clientService.findClient(-1L));
}
@Test
@ -72,11 +72,11 @@ class PremiumStoreApplicationTests {
tankService.deleteAllTanks();
levelService.deleteAllLevels();
Level level = levelService.addLevel(8);
log.info(level.toString());
TankLevel tankLevel = levelService.addLevel(8);
log.info(tankLevel.toString());
Level secondLevel = levelService.addLevel(9);
log.info(secondLevel.toString());
TankLevel secondTankLevel = levelService.addLevel(9);
log.info(secondTankLevel.toString());
Assertions.assertEquals(levelService.findAllLevels().size(), 2);
}
@ -86,10 +86,10 @@ class PremiumStoreApplicationTests {
tankService.deleteAllTanks();
levelService.deleteAllLevels();
List<Level> levels = levelService.findAllLevels();
log.info(levels.toString());
List<TankLevel> tankLevels = levelService.findAllLevels();
log.info(tankLevels.toString());
Assertions.assertEquals(levels.size(), 0);
Assertions.assertEquals(tankLevels.size(), 0);
}
@Test
@ -97,11 +97,11 @@ class PremiumStoreApplicationTests {
tankService.deleteAllTanks();
levelService.deleteAllLevels();
Level firstLevel = levelService.addLevel(8);
Level secondLevel = levelService.addLevel(9);
TankLevel firstTankLevel = levelService.addLevel(8);
TankLevel secondTankLevel = levelService.addLevel(9);
tankService.addTank("ИС-3", nationService.addNation("СССР"), firstLevel, 3700000);
tankService.addTank("E-75", nationService.addNation("Германия"), secondLevel, 5600000);
tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000);
tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000);
List<Tank> tanks = tankService.findAllTanks();
log.info(tanks.toString());
@ -113,11 +113,11 @@ class PremiumStoreApplicationTests {
void testClientCreate() {
clientService.deleteAllClients();
Client firstClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
log.info(firstClient.toString());
GameClient firstGameClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
log.info(firstGameClient.toString());
Client secondClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
log.info(secondClient.toString());
GameClient secondGameClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
log.info(secondGameClient.toString());
Assertions.assertEquals(clientService.findAllClients().size(), 2);
}
@ -128,25 +128,25 @@ class PremiumStoreApplicationTests {
levelService.deleteAllLevels();
clientService.deleteAllClients();
Client firstClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
Client secondClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
GameClient firstGameClient = clientService.addClient("Barbarian", "dsfg@gmail.com", 56000);
GameClient secondGameClient = clientService.addClient("KorbenDallas", "tankoviyGeniy@mail.ru", 37000);
Level firstLevel = levelService.addLevel(8);
Level secondLevel = levelService.addLevel(9);
TankLevel firstTankLevel = levelService.addLevel(8);
TankLevel secondTankLevel = levelService.addLevel(9);
Tank firstTank = tankService.addTank("ИС-3", nationService.addNation("СССР"), firstLevel, 3700000);
Tank secondTank = tankService.addTank("E-75", nationService.addNation("Германия"), secondLevel, 5600000);
Tank firstTank = tankService.addTank("ИС-3", nationService.addNation("СССР"), firstTankLevel, 3700000);
Tank secondTank = tankService.addTank("E-75", nationService.addNation("Германия"), secondTankLevel, 5600000);
Tank tank = tankService.findTank(firstTank.getId());
log.info(tank.toString());
List<Client> newClient = new ArrayList<>();
Collections.addAll(newClient, firstClient, secondClient);
List<GameClient> newGameClient = new ArrayList<>();
Collections.addAll(newGameClient, firstGameClient, secondGameClient);
tank.setName("ИСУ-152");
tank.setLevel(secondLevel);
tank.setLevel(secondTankLevel);
tank.setCost(4100000);
tank.setClients(newClient);
tank.setClients(newGameClient);
log.info(tank.toString());
}