Изменение классов-сервисов.

This commit is contained in:
Programmist73 2023-04-08 23:53:17 +04:00
parent 2844d545ce
commit d0f9fb2bd0
4 changed files with 83 additions and 137 deletions

View File

@ -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> 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<Client> 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<Tank> 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();
}
}

View File

@ -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> 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<Level> 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();
}
}

View File

@ -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> 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<Nation> 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();
}
}

View File

@ -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> 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<Tank> 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<Client> 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();
}
}