надеюсь это все

This commit is contained in:
dasha 2023-04-15 13:25:42 +04:00
parent 0fafffd509
commit a794ee636f
18 changed files with 357 additions and 346 deletions

View File

@ -49,6 +49,7 @@ export default function Orders() {
const handleSubmitCreate = async (e) => { const handleSubmitCreate = async (e) => {
e.preventDefault() e.preventDefault()
console.info('Try to add item'); console.info('Try to add item');
const requestParams = { const requestParams = {
method: "POST", method: "POST",
headers: { headers: {

View File

@ -16,7 +16,7 @@ public class Customer {
private String login; private String login;
@NotBlank(message = "password can't be null or empty") @NotBlank(message = "password can't be null or empty")
private String password; private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.REMOVE) @OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders; private List<Order> orders;
public Customer() { public Customer() {

View File

@ -22,7 +22,12 @@ public class Order {
@JoinColumn(name = "customer_fk") @JoinColumn(name = "customer_fk")
@JsonIgnore @JsonIgnore
private Customer customer; private Customer customer;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade =
{
CascadeType.REMOVE,
CascadeType.MERGE,
CascadeType.PERSIST
}, orphanRemoval = true)
private List<OrderSession> sessions; private List<OrderSession> sessions;
public Order() { public Order() {

View File

@ -26,11 +26,9 @@ public class OrderSession {
public OrderSession(Order order, Session session, Integer count) { public OrderSession(Order order, Session session, Integer count) {
this.order = order; this.order = order;
this.id = new OrderSessionKey(session.getId(), order.getId());
this.id.setOrderId(order.getId());
this.id.setSessionId(session.getId());
this.session = session; this.session = session;
this.count = count; this.count = count;
this.id = new OrderSessionKey(session.getId(), order.getId());
} }
public OrderSessionKey getId() { public OrderSessionKey getId() {

View File

@ -19,7 +19,7 @@ public class Session {
@Column @Column
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Timestamp timestamp; private Timestamp timestamp;
@OneToMany(mappedBy = "session", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @OneToMany(mappedBy = "session", fetch = FetchType.EAGER)
private List<OrderSession> orders; private List<OrderSession> orders;
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cinema_fk") @JoinColumn(name = "cinema_fk")

View File

@ -8,8 +8,4 @@ import org.springframework.data.repository.query.Param;
import java.util.Optional; import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> { public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query("delete from Order p where p.customer.id = :id")
Optional<Customer> deleteCustomerOrders(@Param("id") Long id);
@Query()
void deleteAllCustomers();
} }

View File

@ -1,10 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Customer;
import java.util.Optional;
public interface CustomerRepositoryExtension {
Optional<Customer> deleteCustomerOrders(Long id);
void deleteAllCustomers();
}

View File

@ -1,24 +1,16 @@
package com.labwork1.app.student.repository; package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order; import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
public interface OrderRepository extends JpaRepository<Order, Long> { public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("insert into OrderSession values (orderId, sessionId, count) values (:sessionId, :orderId, :count)") @Query("Select os from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId")
Order addSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId, OrderSession getOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Param("count") Integer count); @Modifying
@Query("delete from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId")
@Query(value = "Select count from OrderSession where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
Integer getCountOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Query(value = "delete from OrderSession where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
void deleteSessionInOrder(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId); void deleteSessionInOrder(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId);
@Query(value = "update OrderSession set count = :count where orderId = :orderId and sessionId = :sessionId",
nativeQuery = true)
void updateSessionInOrder(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId, @Param("count") Integer count);
} }

View File

@ -1,11 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order;
import java.util.Optional;
public interface OrderRepositoryExtension {
Order addOrder(Order order, Long customerId);
Optional<Order> addSession(Long id, Long session, Integer count);
Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count);
}

View File

@ -2,6 +2,11 @@ package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Session; import com.labwork1.app.student.model.Session;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface SessionRepository extends JpaRepository<Session, Long>, SessionRepositoryExtension { import java.util.List;
public interface SessionRepository extends JpaRepository<Session, Long> {
@Query("Select s from Session s where s.capacity > 0")
List<Session> findAllSessionsWithCapacity();
} }

View File

@ -1,12 +0,0 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Session;
import java.util.List;
public interface SessionRepositoryExtension {
Session addSession(Session session, Long cinemaId);
Session deleteSession(Long id);
void deleteAllSessions();
List<Session> findAllSessionsWithCapacity();
}

View File

@ -1,67 +1,63 @@
package com.labwork1.app.student.repository.impl; //package com.labwork1.app.student.repository.impl;
//
import com.labwork1.app.student.model.Customer; //import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order; //import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession; //import com.labwork1.app.student.model.OrderSession;
import com.labwork1.app.student.model.Session; //import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.repository.CustomerRepository; //import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.student.repository.CustomerRepositoryExtension; //import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.student.repository.OrderRepository; //import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManager; //import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContext; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Lazy; //
//import java.util.List;
import java.util.List; //import java.util.Optional;
import java.util.Optional; //
//public class CustomerRepositoryImpl {
public class CustomerRepositoryImpl implements CustomerRepositoryExtension { // @Lazy
@Autowired // private CustomerRepository customerRepository;
@Lazy // @Lazy
private CustomerRepository customerRepository; // private OrderRepository orderRepository;
@Autowired //
@Lazy // @PersistenceContext
private OrderRepository orderRepository; // private EntityManager em;
//
@PersistenceContext // public Optional<Customer> deleteCustomerOrders(Long id) {
private EntityManager em; // final Optional<Customer> currentCustomer = customerRepository.findById(id);
// if (currentCustomer.isPresent()) {
@Override // final List<Order> currentCustomerOrders = currentCustomer.get().getOrders();
public Optional<Customer> deleteCustomerOrders(Long id) { //
final Optional<Customer> currentCustomer = customerRepository.findById(id); // for (int i = 0; i < currentCustomerOrders.size(); i++) {
if (currentCustomer.isPresent()) { // final Optional<Order> tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId());
final List<Order> currentCustomerOrders = currentCustomer.get().getOrders(); // if (tempOrder.isPresent()) {
// final Order currentOrder = tempOrder.get();
for (int i = 0; i < currentCustomerOrders.size(); i++) { // List<OrderSession> orderSessionList = em
final Optional<Order> tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId()); // .createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class)
if (tempOrder.isPresent()) { // .setParameter("id", id)
final Order currentOrder = tempOrder.get(); // .getResultList();
List<OrderSession> orderSessionList = em // for (int j = 0; j < orderSessionList.size(); j++) {
.createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class) // final Session currentSession = orderSessionList.get(j).getSession();
.setParameter("id", id) // currentOrder.getSessions().remove(orderSessionList.get(j));
.getResultList(); // currentSession.getOrders().remove(orderSessionList.get(j));
for (int j = 0; j < orderSessionList.size(); j++) { // em.remove(orderSessionList.get(j));
final Session currentSession = orderSessionList.get(j).getSession(); // em.merge(currentSession);
currentOrder.getSessions().remove(orderSessionList.get(j)); // }
currentSession.getOrders().remove(orderSessionList.get(j)); // em.merge(currentOrder);
em.remove(orderSessionList.get(j)); // }
em.merge(currentSession); // }
} // em.remove(currentCustomer.get());
em.merge(currentOrder); // }
} // return currentCustomer;
} // }
em.remove(currentCustomer.get()); //
} //
return currentCustomer; // public void deleteAllCustomers() {
} // List<Customer> customers = em
// .createQuery("select c from Customer c", Customer.class)
@Override // .getResultList();
public void deleteAllCustomers() { // for (var customer : customers) {
List<Customer> customers = em // deleteCustomerOrders(customer.getId());
.createQuery("select c from Customer c", Customer.class) // }
.getResultList(); // }
for (var customer : customers) { //}
deleteCustomerOrders(customer.getId());
}
}
}

View File

@ -1,105 +1,104 @@
package com.labwork1.app.student.repository.impl; //package com.labwork1.app.student.repository.impl;
//
import com.labwork1.app.student.model.*; //import com.labwork1.app.student.model.*;
import com.labwork1.app.student.repository.CustomerRepository; //import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.student.repository.OrderRepository; //import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.student.repository.OrderRepositoryExtension; //import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.student.repository.SessionRepository; //import com.labwork1.app.student.service.CustomerNotFoundException;
import com.labwork1.app.student.service.CustomerNotFoundException; //import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManager; //import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContext; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Lazy; //import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional; //
//import java.util.Optional;
import java.util.Optional; //
//public class OrderRepositoryImpl {
public class OrderRepositoryImpl implements OrderRepositoryExtension { //
@Autowired // @Lazy
@Lazy // private CustomerRepository customerRepository;
private CustomerRepository customerRepository; //
@Autowired // @Lazy
@Lazy // private OrderRepository orderRepository;
private OrderRepository orderRepository; //
@Autowired // @Lazy
@Lazy // private SessionRepository sessionRepository;
private SessionRepository sessionRepository; // @PersistenceContext
@PersistenceContext // private EntityManager em;
private EntityManager em; //
@Override // public Order addOrder(Order order, Long customerId) {
public Order addOrder(Order order, Long customerId) { // final Optional<Customer> customer = customerRepository.findById(customerId);
final Optional<Customer> customer = customerRepository.findById(customerId); // if (customer.isEmpty()) {
if (customer.isEmpty()) { // throw new CustomerNotFoundException(customerId);
throw new CustomerNotFoundException(customerId); // }
} // order.setCustomer(customer.get());
order.setCustomer(customer.get()); // em.persist(order);
em.persist(order); // em.merge(customer.get());
em.merge(customer.get()); // return order;
return order; // }
} //
//
@Override // @Transactional
@Transactional // public Optional<Order> addSession(Long id, Long session, Integer count) {
public Optional<Order> addSession(Long id, Long session, Integer count) { // if (session <= 0 || count <= 0) {
if (session <= 0 || count <= 0) { // throw new IllegalArgumentException("addOrder empty fields");
throw new IllegalArgumentException("addOrder empty fields"); // }
} // Optional<Order> optionalOrder = orderRepository.findById(id);
Optional<Order> optionalOrder = orderRepository.findById(id); // Optional<Session> optionalSession = sessionRepository.findById(session);
Optional<Session> optionalSession = sessionRepository.findById(session); // if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { // return optionalOrder;
return optionalOrder; // }
} // final Session currentSession = optionalSession.get();
final Session currentSession = optionalSession.get(); // final Order currentOrder = optionalOrder.get();
final Order currentOrder = optionalOrder.get(); // OrderSession orderSession = em.find(OrderSession.class,
OrderSession orderSession = em.find(OrderSession.class, // new OrderSessionKey(currentSession.getId(), currentOrder.getId()));
new OrderSessionKey(currentSession.getId(), currentOrder.getId())); //
// if (currentSession.getCapacity() < count ||
if (currentSession.getCapacity() < count || // (orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) {
(orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) { // throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s", // currentSession.getCapacity(), count));
currentSession.getCapacity(), count)); // }
} // if (orderSession == null)
if (orderSession == null) // orderSession = new OrderSession(currentOrder, currentSession, count);
orderSession = new OrderSession(currentOrder, currentSession, count); // else if (orderSession.getCount() + count <= currentSession.getMaxCount()) {
else if (orderSession.getCount() + count <= currentSession.getMaxCount()) { // orderSession.setCount(orderSession.getCount() + count);
orderSession.setCount(orderSession.getCount() + count); // }
} //
// currentOrder.addSession(orderSession);
currentOrder.addSession(orderSession); // currentSession.addOrder(orderSession);
currentSession.addOrder(orderSession); // currentSession.setCapacity(currentSession.getCapacity() - count);
currentSession.setCapacity(currentSession.getCapacity() - count); // em.merge(currentSession);
em.merge(currentSession); // em.merge(currentOrder);
em.merge(currentOrder); // em.merge(orderSession);
em.merge(orderSession); // return orderRepository.findById(id);
return orderRepository.findById(id); // }
} //
// @Override
@Override // public Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count) {
public Optional<Order> deleteSessionInOrder(Long id, Long session, Integer count) { // final Optional<Order> optionalOrder = orderRepository.findById(id);
final Optional<Order> optionalOrder = orderRepository.findById(id); // final Optional<Session> optionalSession = sessionRepository.findById(session);
final Optional<Session> optionalSession = sessionRepository.findById(session); // if (optionalOrder.isEmpty() || optionalSession.isEmpty()) {
if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { // return optionalOrder;
return optionalOrder; // }
} // final Order currentOrder = optionalOrder.get();
final Order currentOrder = optionalOrder.get(); // final Session currentSession = optionalSession.get();
final Session currentSession = optionalSession.get(); //
// OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id));
OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id)); // if (orderSession == null)
if (orderSession == null) // return optionalOrder;
return optionalOrder; //
// if (count >= orderSession.getCount()) {
if (count >= orderSession.getCount()) { // currentOrder.getSessions().remove(orderSession);
currentOrder.getSessions().remove(orderSession); // currentSession.getOrders().remove(orderSession);
currentSession.getOrders().remove(orderSession); // currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount());
currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount()); // em.remove(orderSession);
em.remove(orderSession); // } else {
} else { // orderSession.setCount(orderSession.getCount() - count);
orderSession.setCount(orderSession.getCount() - count); // currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount());
currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount()); // em.merge(orderSession);
em.merge(orderSession); // em.merge(currentSession);
em.merge(currentSession); // }
} //
// return orderRepository.findById(id);
return orderRepository.findById(id); // }
} //}
}

View File

@ -1,74 +1,73 @@
package com.labwork1.app.student.repository.impl; //package com.labwork1.app.student.repository.impl;
//
import com.labwork1.app.student.model.Cinema; //import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.OrderSession; //import com.labwork1.app.student.model.OrderSession;
import com.labwork1.app.student.model.Session; //import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.repository.CinemaRepository; //import com.labwork1.app.student.repository.CinemaRepository;
import com.labwork1.app.student.repository.SessionRepository; //import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.student.repository.SessionRepositoryExtension; //import com.labwork1.app.student.service.CinemaNotFoundException;
import com.labwork1.app.student.service.CinemaNotFoundException; //import com.labwork1.app.student.service.SessionNotFoundException;
import com.labwork1.app.student.service.SessionNotFoundException; //import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManager; //import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContext; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Lazy; //
//import java.util.List;
import java.util.List; //import java.util.Optional;
import java.util.Optional; //
//public class SessionRepositoryImpl implements SessionRepositoryExtension {
public class SessionRepositoryImpl implements SessionRepositoryExtension { // @Autowired
@Autowired // @Lazy
@Lazy // private SessionRepository sessionRepository;
private SessionRepository sessionRepository; // @Autowired
@Autowired // @Lazy
@Lazy // private CinemaRepository cinemaRepository;
private CinemaRepository cinemaRepository; // @PersistenceContext
@PersistenceContext // private EntityManager em;
private EntityManager em; // @Override
@Override // public Session addSession(Session session, Long cinemaId) {
public Session addSession(Session session, Long cinemaId) { // if (session == null) return null;
if (session == null) return null; // final Optional<Cinema> cinema = cinemaRepository.findById(cinemaId);
final Optional<Cinema> cinema = cinemaRepository.findById(cinemaId); // if (cinema.isEmpty()) {
if (cinema.isEmpty()) { // throw new CinemaNotFoundException(cinemaId);
throw new CinemaNotFoundException(cinemaId); // }
} // session.setCinema(cinema.get());
session.setCinema(cinema.get()); // em.persist(session);
em.persist(session); // em.merge(cinema.get());
em.merge(cinema.get()); // return session;
return session; // }
} //
// @Override
@Override // public Session deleteSession(Long id) {
public Session deleteSession(Long id) { // final Optional<Session> optionalSession = sessionRepository.findById(id);
final Optional<Session> optionalSession = sessionRepository.findById(id); // if (optionalSession.isEmpty()) {
if (optionalSession.isEmpty()) { // throw new SessionNotFoundException(id);
throw new SessionNotFoundException(id); // }
} // final Session currentSession = optionalSession.get();
final Session currentSession = optionalSession.get(); // int size = currentSession.getOrders().size();
int size = currentSession.getOrders().size(); // for (int i = 0; i < size; i++) {
for (int i = 0; i < size; i++) { // OrderSession temp = currentSession.getOrders().get(0);
OrderSession temp = currentSession.getOrders().get(0); // temp.getSession().removeOrder(temp);
temp.getSession().removeOrder(temp); // temp.getOrder().removeSession(temp);
temp.getOrder().removeSession(temp); // em.remove(temp);
em.remove(temp); // }
} // em.remove(currentSession);
em.remove(currentSession); // return currentSession;
return currentSession; // }
} //
// @Override
@Override // public void deleteAllSessions() {
public void deleteAllSessions() { // List<Session> sessions = em
List<Session> sessions = em // .createQuery("select s from Session s", Session.class)
.createQuery("select s from Session s", Session.class) // .getResultList();
.getResultList(); // for (var session : sessions) {
for (var session : sessions) { // deleteSession(session.getId());
deleteSession(session.getId()); // }
} // }
} //
// @Override
@Override // public List<Session> findAllSessionsWithCapacity() {
public List<Session> findAllSessionsWithCapacity() { // return em.createQuery("select t from Session t where capacity > 0", Session.class)
return em.createQuery("select t from Session t where capacity > 0", Session.class) // .getResultList();
.getResultList(); // }
} //}
}

View File

@ -1,6 +1,8 @@
package com.labwork1.app.student.service; package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Customer; import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.OrderSession;
import com.labwork1.app.student.repository.CustomerRepository; import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidatorUtil; import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -12,11 +14,12 @@ import java.util.Optional;
@Service @Service
public class CustomerService { public class CustomerService {
private final CustomerRepository customerRepository; private final CustomerRepository customerRepository;
private final SessionService sessionService;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository, public CustomerService(CustomerRepository customerRepository, SessionService sessionService, ValidatorUtil validatorUtil) {
ValidatorUtil validatorUtil) {
this.customerRepository = customerRepository; this.customerRepository = customerRepository;
this.sessionService = sessionService;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@ -49,12 +52,25 @@ public class CustomerService {
@Transactional @Transactional
public Customer deleteCustomer(Long id) { public Customer deleteCustomer(Long id) {
final Optional<Customer> customer = customerRepository.deleteCustomerOrders(id); final Customer customer = findCustomer(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id)); // заказы покупателя
final List<Order> orders = customer.getOrders();
for (Order order : orders) {
// сеансы в заказе
for (OrderSession orderSession : order.getSessions()) {
// освобождаем сеансы
sessionService.updateSession(orderSession.getSession().getId(),
orderSession.getSession().getPrice(), orderSession.getSession().getMaxCount());
}
}
customerRepository.deleteById(id);
return customer;
} }
@Transactional @Transactional
public void deleteAllCustomers() { public void deleteAllCustomers() {
customerRepository.deleteAllCustomers(); customerRepository.deleteAll();
} }
} }

View File

@ -36,29 +36,28 @@ public class OrderService {
@Transactional @Transactional
public Order addSession(Long id, Long sessionId, Integer count) { public Order addSession(Long id, Long sessionId, Integer count) {
Optional<Order> optionalOrder = orderRepository.findById(id);
final Session currentSession = sessionService.findSession(sessionId); final Session currentSession = sessionService.findSession(sessionId);
if (optionalOrder.isEmpty()) { final Order currentOrder = findOrder(id);
throw new OrderNotFoundException(id); final OrderSession currentOrderSession = orderRepository.getOrderSession(id, sessionId);
}
Order currentOrder = optionalOrder.get();
final Integer countOrderSession = orderRepository.getCountOrderSession(id, sessionId);
if (currentSession.getCapacity() < count || if (currentSession.getCapacity() < count ||
(countOrderSession != null && countOrderSession + count > currentSession.getMaxCount())) { (currentOrderSession != null && currentOrderSession.getCount() + count > currentSession.getMaxCount())) {
throw new IllegalArgumentException(String.format("No more tickets in sessionId. Capacity: %1$s. Count: %2$s", throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s",
currentSession.getCapacity(), count)); currentSession.getCapacity(), count));
} }
currentSession.setCapacity(currentSession.getCapacity() - count);
if (countOrderSession == null) { /*final Session updatedSession = sessionService.updateSession(currentSession.getId(),
currentSession.getPrice(), currentSession.getCapacity() - count);*/
if (currentOrderSession == null) {
currentOrder.addSession(new OrderSession(currentOrder, currentSession, count)); currentOrder.addSession(new OrderSession(currentOrder, currentSession, count));
return orderRepository.save(currentOrder);
} }
else if (countOrderSession + count <= currentSession.getMaxCount()) { else if (currentOrderSession.getCount() + count <= currentSession.getMaxCount()) {
orderRepository.delete(currentOrder); currentOrder.removeSession(currentOrderSession);
orderRepository.addSession(id, sessionId, countOrderSession + count); currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() + count));
} }
return optionalOrder.get(); return orderRepository.save(currentOrder);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
@ -75,24 +74,38 @@ public class OrderService {
@Transactional @Transactional
public Order deleteOrder(Long id) { public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id); final Order currentOrder = findOrder(id);
// сеансы в заказе
for (OrderSession orderSession : currentOrder.getSessions()) {
// освобождаем сеансы
sessionService.updateSession(orderSession.getSession().getId(),
orderSession.getSession().getPrice(), orderSession.getSession().getMaxCount());
}
orderRepository.delete(currentOrder); orderRepository.delete(currentOrder);
return currentOrder; return currentOrder;
} }
@Transactional @Transactional
public void deleteSessionInOrder(Long id, Long session, Integer count) { public Order deleteSessionInOrder(Long id, Long session, Integer count) {
final Order currentOrder = findOrder(id); final Order currentOrder = findOrder(id);
final Session currentSession = sessionService.findSession(session); final Session currentSession = sessionService.findSession(session);
Integer countOrderSession = orderRepository.getCountOrderSession(id, session); final OrderSession currentOrderSession = orderRepository.getOrderSession(id, session);
if (countOrderSession == null) if (currentOrderSession == null)
throw new EntityNotFoundException(); throw new EntityNotFoundException();
if (count >= countOrderSession) {
orderRepository.deleteSessionInOrder(id, session); if (count >= currentOrderSession.getCount()) {
currentOrder.removeSession(currentOrderSession);
sessionService.updateSession(session, currentSession.getPrice(), sessionService.updateSession(session, currentSession.getPrice(),
currentSession.getCapacity() + countOrderSession); currentSession.getCapacity() + currentOrderSession.getCount());
} }
else else {
orderRepository.updateSessionInOrder(id, session, count); currentOrder.removeSession(currentOrderSession);
currentSession.setCapacity(currentSession.getCapacity() + count);
currentOrder.addSession(new OrderSession(currentOrder, currentSession,
currentOrderSession.getCount() - count));
}
return orderRepository.save(currentOrder);
} }
@Transactional @Transactional

View File

@ -1,5 +1,6 @@
package com.labwork1.app.student.service; package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Cinema;
import com.labwork1.app.student.model.Session; import com.labwork1.app.student.model.Session;
import com.labwork1.app.student.repository.SessionRepository; import com.labwork1.app.student.repository.SessionRepository;
import com.labwork1.app.util.validation.ValidatorUtil; import com.labwork1.app.util.validation.ValidatorUtil;
@ -7,24 +8,29 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
public class SessionService { public class SessionService {
private final SessionRepository sessionRepository; private final SessionRepository sessionRepository;
private final CinemaService cinemaService;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public SessionService(SessionRepository sessionRepository, public SessionService(SessionRepository sessionRepository,
ValidatorUtil validatorUtil) { CinemaService cinemaService, ValidatorUtil validatorUtil) {
this.sessionRepository = sessionRepository; this.sessionRepository = sessionRepository;
this.cinemaService = cinemaService;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
} }
@Transactional @Transactional
public Session addSession(Double price, Timestamp date, Long cinemaId, Integer capacity) { public Session addSession(Double price, Timestamp date, Long cinemaId, Integer capacity) {
final Session session = new Session(price, date, capacity); final Session session = new Session(price, date, capacity);
final Cinema cinema = cinemaService.findCinema(cinemaId);
session.setCinema(cinema);
validatorUtil.validate(session); validatorUtil.validate(session);
return sessionRepository.addSession(session, cinemaId); return sessionRepository.save(session);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
@ -42,6 +48,7 @@ public class SessionService {
public Session updateSession(Long id, Double price, Integer capacity) { public Session updateSession(Long id, Double price, Integer capacity) {
final Session currentSession = findSession(id); final Session currentSession = findSession(id);
currentSession.setPrice(price); currentSession.setPrice(price);
// для обновления полей класса (цены)
if (capacity != -1) if (capacity != -1)
currentSession.setCapacity(capacity); currentSession.setCapacity(capacity);
validatorUtil.validate(currentSession); validatorUtil.validate(currentSession);
@ -50,12 +57,18 @@ public class SessionService {
@Transactional @Transactional
public Session deleteSession(Long id) { public Session deleteSession(Long id) {
return sessionRepository.deleteSession(id); final Session currentSession = findSession(id);
// все равно сеанс не удалился бы, который участвует в заказах
// для отслеживания операции с ошибкой
if (currentSession.getOrders().size() > 0)
throw new IllegalArgumentException();
sessionRepository.delete(currentSession);
return currentSession;
} }
@Transactional @Transactional
public void deleteAllSessions() { public void deleteAllSessions() {
sessionRepository.deleteAllSessions(); sessionRepository.deleteAll();
} }
@Transactional @Transactional

View File

@ -11,9 +11,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List;
@SpringBootTest @SpringBootTest
public class JpaCustomerTests { public class JpaCustomerTests {
@ -73,7 +73,7 @@ public class JpaCustomerTests {
orderService.addSession(order2.getId(), session2.getId(), 5); orderService.addSession(order2.getId(), session2.getId(), 5);
Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 5); Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 5);
Assertions.assertThrows(InvalidDataAccessApiUsageException.class, () -> Assertions.assertThrows(IllegalArgumentException.class, () ->
orderService.addSession(order2.getId(), session2.getId(), 6)); orderService.addSession(order2.getId(), session2.getId(), 6));
// у заказа 1 сеанс // у заказа 1 сеанс
@ -100,22 +100,33 @@ public class JpaCustomerTests {
// 3 сеанса всего // 3 сеанса всего
final Session session3 = sessionService.addSession(300.0, final Session session3 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10); new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
// осталось 2 сеанса, у заказа2 0 сеансов // удалили заказ2, у которого был сеанс1
sessionService.deleteSession(session1.getId()); orderService.deleteOrder(order2.getId());
Assertions.assertEquals(sessionService.findAllSessions().size(), 2); Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
Assertions.assertEquals(orderService // создали 3 заказ у 2 покупателя
.findOrder(order2.getId()).getSessions().size(), 0); final Order order3 = orderService
.addOrder(customerService.findCustomer(customer2.getId()).getId());
orderService.addSession(order3.getId(), session2.getId(), 2);
orderService.addSession(order3.getId(), session3.getId(), 8);
orderService.addSession(order3.getId(), session1.getId(), 8);
// 2-ой покупатель удален // 2-ой покупатель удален
// 0 заказов после его удаления // 0 заказов после его удаления
Assertions.assertEquals(orderService.findAllOrders().size(), 1); Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 8);
customerService.deleteCustomer(customer2.getId()); customerService.deleteCustomer(customer2.getId());
Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId())); Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order2.getId())); Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0); Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 10);
Assertions.assertEquals(sessionService.findSession(session3.getId()).getCapacity(), 10);
Assertions.assertEquals(sessionService.findSession(session3.getId()), session3); Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
cinemaService.deleteCinema(cinema2.getId()); cinemaService.deleteCinema(cinema2.getId());
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
} }
} }