From d0f9fb2bd066a46580275b27353dab5fe21bf253 Mon Sep 17 00:00:00 2001 From: Programmist73 Date: Sat, 8 Apr 2023 23:53:17 +0400 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=BE=D0=B2-?= =?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../premium_store/service/ClientService.java | 67 ++++++----------- .../premium_store/service/LevelService.java | 30 +++----- .../premium_store/service/NationService.java | 49 ++++++------ .../premium_store/service/TankService.java | 74 +++++++------------ 4 files changed, 83 insertions(+), 137 deletions(-) diff --git a/spring_online_calculator/src/main/java/premium_store/service/ClientService.java b/spring_online_calculator/src/main/java/premium_store/service/ClientService.java index 747228a..1f596d9 100644 --- a/spring_online_calculator/src/main/java/premium_store/service/ClientService.java +++ b/spring_online_calculator/src/main/java/premium_store/service/ClientService.java @@ -2,80 +2,61 @@ package premium_store.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; import premium_store.model.Client; import premium_store.model.Tank; +import premium_store.repository.ClientRepository; +import premium_store.service.exception.ClientNotFoundException; +import premium_store.util.validation.ValidatorUtil; -import javax.persistence.EntityManager; -import javax.persistence.EntityNotFoundException; -import javax.persistence.PersistenceContext; import java.util.List; +import java.util.Optional; @Service public class ClientService { - @PersistenceContext - private EntityManager em; + private final ClientRepository clientRepository; + private final ValidatorUtil validatorUtil; + + public ClientService(ClientRepository clientRepository, ValidatorUtil validatorUtil){ + this.clientRepository = clientRepository; + this.validatorUtil = validatorUtil; + } @Transactional public Client addClient(String newNickName, String newEmail, Integer newBallance) { - if (!StringUtils.hasText(newNickName) || !StringUtils.hasText(newEmail)) { - throw new IllegalArgumentException("NickName or newEmail is zero or empty"); - } - final Client client = new Client(newNickName, newEmail, newBallance); - em.persist(client); + validatorUtil.validate(client); - return client; + return clientRepository.save(client); } @Transactional(readOnly = true) public Client findClient(Long id) { - final Client Client = em.find(Client.class, id); + final Optional client = clientRepository.findById(id); - if (Client == null) { - throw new EntityNotFoundException(String.format("Client with id [%s] is not found", id)); - } - - return Client; + return client.orElseThrow(() -> new ClientNotFoundException(id)); } @Transactional(readOnly = true) public List findAllClients() { - return em.createQuery("select c from Client c", Client.class) - .getResultList(); + return clientRepository.findAll(); } @Transactional public Client updateClient(Long id, String newNickName, String newEmail, Integer newBalance, List newTanks) { - if (id <= 0) { - throw new IllegalArgumentException("Invalid id"); - } - final Client currentClient = findClient(id); + currentClient.setNickName(newNickName); + currentClient.setEmail(newEmail); + currentClient.setBalance(newBalance); + currentClient.setTanks(newTanks); + validatorUtil.validate(currentClient); - if (StringUtils.hasText(newNickName)){ - currentClient.setNickName(newNickName); - } - - if(StringUtils.hasText(newEmail)){ - currentClient.setEmail(newEmail); - } - - if(newBalance != null){ - currentClient.setBalance(newBalance); - } - - if(newTanks != null){ - currentClient.setTanks(newTanks); - } - - return em.merge(currentClient); + return clientRepository.save(currentClient); } @Transactional public Client deleteClient(Long id) { final Client currentClient = findClient(id); - em.remove(currentClient); + clientRepository.delete(currentClient); return currentClient; } @@ -83,6 +64,6 @@ public class ClientService { //прямой sql-запрос на удаление всех записей в таблице @Transactional public void deleteAllClients() { - em.createQuery("Delete from Client").executeUpdate(); + clientRepository.deleteAll(); } } diff --git a/spring_online_calculator/src/main/java/premium_store/service/LevelService.java b/spring_online_calculator/src/main/java/premium_store/service/LevelService.java index dfc3d9f..7466e60 100644 --- a/spring_online_calculator/src/main/java/premium_store/service/LevelService.java +++ b/spring_online_calculator/src/main/java/premium_store/service/LevelService.java @@ -4,17 +4,15 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import premium_store.model.Level; import premium_store.repository.LevelRepository; +import premium_store.service.exception.LevelNotFoundException; import premium_store.util.validation.ValidatorUtil; -import javax.persistence.EntityManager; -import javax.persistence.EntityNotFoundException; -import javax.persistence.PersistenceContext; import java.util.List; +import java.util.Optional; //сервис после удаления EntityManager и добавления нашего репозитория. То есть у него уже все методы работы с полями прописаны за нас? @Service public class LevelService { - @PersistenceContext private final LevelRepository levelRepository; private final ValidatorUtil validatorUtil; @@ -31,45 +29,39 @@ public class LevelService { return levelRepository.save(level); } + //здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null @Transactional(readOnly = true) public Level findLevel(Long id) { - final Level level = em.find(Level.class, id); + final Optional level = levelRepository.findById(id); - if (level == null) { - throw new EntityNotFoundException(String.format("Level with id [%s] is not found", id)); - } - - return level; + //благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения + return level.orElseThrow(() -> new LevelNotFoundException(id)); } @Transactional(readOnly = true) public List findAllLevels() { - return em.createQuery("select s from Level s", Level.class) - .getResultList(); + return levelRepository.findAll(); } @Transactional public Level updateLevel(Long id, int newLevel) { - if (newLevel <= 0) { - throw new IllegalArgumentException("Level name is zero or less"); - } - final Level currentLevel = findLevel(id); currentLevel.setLevel(newLevel); + validatorUtil.validate(currentLevel); - return em.merge(currentLevel); + return levelRepository.save(currentLevel); } @Transactional public Level deleteLevel(Long id) { final Level currentLevel = findLevel(id); - em.remove(currentLevel); + levelRepository.delete(currentLevel); return currentLevel; } @Transactional public void deleteAllLevels() { - em.createQuery("Delete from Level").executeUpdate(); + levelRepository.deleteAll(); } } diff --git a/spring_online_calculator/src/main/java/premium_store/service/NationService.java b/spring_online_calculator/src/main/java/premium_store/service/NationService.java index 5e5f966..aa5a74d 100644 --- a/spring_online_calculator/src/main/java/premium_store/service/NationService.java +++ b/spring_online_calculator/src/main/java/premium_store/service/NationService.java @@ -2,70 +2,65 @@ package premium_store.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; import premium_store.model.Nation; +import premium_store.repository.NationRepository; +import premium_store.service.exception.NationNotFoundException; +import premium_store.util.validation.ValidatorUtil; -import javax.persistence.EntityManager; -import javax.persistence.EntityNotFoundException; -import javax.persistence.PersistenceContext; import java.util.List; +import java.util.Optional; @Service public class NationService { - @PersistenceContext - private EntityManager em; + private final NationRepository nationRepository; + private final ValidatorUtil validatorUtil; + + public NationService(NationRepository nationRepository, ValidatorUtil validatorUtil){ + this.nationRepository = nationRepository; + this.validatorUtil = validatorUtil; + } @Transactional public Nation addNation(String nameNation){ - if(!StringUtils.hasText(nameNation)){ - throw new IllegalArgumentException("The name of the nation is null or empty"); - } - final Nation nation = new Nation(nameNation); - em.persist(nation); + validatorUtil.validate(nation); - return nation; + return nationRepository.save(nation); } + //здесь используем Optional - спец. тип данных, позволяющий определять, вернулось ли что-то при вызове метода, или вернулся null @Transactional(readOnly = true) public Nation findNation(Long id){ - final Nation nation = em.find(Nation.class, id); + final Optional nation = nationRepository.findById(id); - if(nation == null){ - throw new EntityNotFoundException(String.format("Nation with id [%s] is not found", id)); - } - - return nation; + //благодаря Optional можем вызвать orElseThrow, который в случае null сделает проброс кастомного исключения + return nation.orElseThrow(() -> new NationNotFoundException(id)); } @Transactional(readOnly = true) public List findAllNations() { - return em.createQuery("select n from Nation n", Nation.class) - .getResultList(); + return nationRepository.findAll(); } @Transactional public Nation updateNation(Long id, String newNation) { - if (!StringUtils.hasText(newNation)) { - throw new IllegalArgumentException("Student name is null or empty"); - } - final Nation currentNation = findNation(id); currentNation.setNation(newNation); + validatorUtil.validate(currentNation); - return em.merge(currentNation); + return nationRepository.save(currentNation); } @Transactional public Nation deleteNAtion(Long id) { final Nation currentNation = findNation(id); - em.remove(currentNation); + nationRepository.delete(currentNation); return currentNation; } @Transactional public void deleteAllNations() { - em.createQuery("delete from Nation").executeUpdate(); + nationRepository.deleteAll(); } } diff --git a/spring_online_calculator/src/main/java/premium_store/service/TankService.java b/spring_online_calculator/src/main/java/premium_store/service/TankService.java index ab12d58..38e88b4 100644 --- a/spring_online_calculator/src/main/java/premium_store/service/TankService.java +++ b/spring_online_calculator/src/main/java/premium_store/service/TankService.java @@ -2,94 +2,72 @@ package premium_store.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; import premium_store.model.Client; import premium_store.model.Level; import premium_store.model.Nation; import premium_store.model.Tank; +import premium_store.repository.TankRepository; +import premium_store.service.exception.TankNotFoundException; +import premium_store.util.validation.ValidatorUtil; -import javax.persistence.EntityManager; -import javax.persistence.EntityNotFoundException; -import javax.persistence.PersistenceContext; import java.util.List; +import java.util.Optional; @Service public class TankService { - @PersistenceContext - private EntityManager em; + private final TankRepository tankRepository; + private final ValidatorUtil validatorUtil; + + public TankService(TankRepository tankRepository, ValidatorUtil validatorUtil){ + this.tankRepository = tankRepository; + this.validatorUtil = validatorUtil; + } @Transactional public Tank addTank(String newName, Nation newNation, Level newLevel, int newCost) { - if (!StringUtils.hasText(newName) || newNation == null || newLevel == null || newCost <= 0) { - throw new IllegalArgumentException("New Name, new Nation, new Level or newCost is zero or empty"); - } - final Tank tank = new Tank(newName, newNation, newLevel, newCost); - em.persist(tank); + validatorUtil.validate(tank); - return tank; + return tankRepository.save(tank); } @Transactional(readOnly = true) public Tank findTank(Long id) { - final Tank Tank = em.find(Tank.class, id); + final Optional tank = tankRepository.findById(id); - if (Tank == null) { - throw new EntityNotFoundException(String.format("Tank with id [%s] is not found", id)); - } - - return Tank; + return tank.orElseThrow(() -> new TankNotFoundException(id)); } @Transactional(readOnly = true) public List findAllTanks() { - return em.createQuery("select t from Tank t", Tank.class) - .getResultList(); + return tankRepository.findAll(); } @Transactional public Tank updateTank(Long id, String newName, Nation newNation, Level newLevel, int newCost, List newClients) { - if (id <= 0) { - throw new IllegalArgumentException("Invalid id"); - } - final Tank currentTank = findTank(id); + currentTank.setName(newName); + currentTank.setNation(newNation); + currentTank.setLevel(newLevel); + currentTank.setCost(newCost); + currentTank.setClients(newClients); + validatorUtil.validate(currentTank); - if (StringUtils.hasText(newName)){ - currentTank.setName(newName); - } - - if(newNation != null){ - currentTank.setNation(newNation); - } - - if(newLevel != null){ - currentTank.setLevel(newLevel); - } - - if(newCost > 0){ - currentTank.setCost(newCost); - } - - if(newClients != null){ - currentTank.setClients(newClients); - } - - return em.merge(currentTank); + return tankRepository.save(currentTank); } @Transactional public Tank deleteTank(Long id) { final Tank currentTank = findTank(id); - em.remove(currentTank); + tankRepository.delete(currentTank); return currentTank; } - //прямой sql-запрос на удаление всех записей в таблице + //запрос на удаление всех записей в таблице @Transactional public void deleteAllTanks() { - em.createQuery("Delete from Tank").executeUpdate(); + tankRepository.deleteAll(); } }