From a794ee636f5f189ee3d74970e519b913223bf19a Mon Sep 17 00:00:00 2001 From: dasha Date: Sat, 15 Apr 2023 13:25:42 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BD=D0=B0=D0=B4=D0=B5=D1=8E=D1=81=D1=8C=20?= =?UTF-8?q?=D1=8D=D1=82=D0=BE=20=D0=B2=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- front/src/pages/Orders.jsx | 1 + .../labwork1/app/student/model/Customer.java | 2 +- .../com/labwork1/app/student/model/Order.java | 7 +- .../app/student/model/OrderSession.java | 4 +- .../labwork1/app/student/model/Session.java | 2 +- .../repository/CustomerRepository.java | 4 - .../CustomerRepositoryExtension.java | 10 - .../student/repository/OrderRepository.java | 20 +- .../repository/OrderRepositoryExtension.java | 11 - .../student/repository/SessionRepository.java | 7 +- .../SessionRepositoryExtension.java | 12 - .../impl/CustomerRepositoryImpl.java | 130 ++++++----- .../repository/impl/OrderRepositoryImpl.java | 209 +++++++++--------- .../impl/SessionRepositoryImpl.java | 147 ++++++------ .../app/student/service/CustomerService.java | 26 ++- .../app/student/service/OrderService.java | 59 +++-- .../app/student/service/SessionService.java | 21 +- .../com/labwork1/app/JpaCustomerTests.java | 31 ++- 18 files changed, 357 insertions(+), 346 deletions(-) delete mode 100644 src/main/java/com/labwork1/app/student/repository/CustomerRepositoryExtension.java delete mode 100644 src/main/java/com/labwork1/app/student/repository/OrderRepositoryExtension.java delete mode 100644 src/main/java/com/labwork1/app/student/repository/SessionRepositoryExtension.java diff --git a/front/src/pages/Orders.jsx b/front/src/pages/Orders.jsx index ed91c68..6aa4422 100644 --- a/front/src/pages/Orders.jsx +++ b/front/src/pages/Orders.jsx @@ -49,6 +49,7 @@ export default function Orders() { const handleSubmitCreate = async (e) => { e.preventDefault() console.info('Try to add item'); + const requestParams = { method: "POST", headers: { diff --git a/src/main/java/com/labwork1/app/student/model/Customer.java b/src/main/java/com/labwork1/app/student/model/Customer.java index 73304c3..3aa56d9 100644 --- a/src/main/java/com/labwork1/app/student/model/Customer.java +++ b/src/main/java/com/labwork1/app/student/model/Customer.java @@ -16,7 +16,7 @@ public class Customer { private String login; @NotBlank(message = "password can't be null or empty") 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 orders; public Customer() { diff --git a/src/main/java/com/labwork1/app/student/model/Order.java b/src/main/java/com/labwork1/app/student/model/Order.java index b741ba3..c33f811 100644 --- a/src/main/java/com/labwork1/app/student/model/Order.java +++ b/src/main/java/com/labwork1/app/student/model/Order.java @@ -22,7 +22,12 @@ public class Order { @JoinColumn(name = "customer_fk") @JsonIgnore 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 sessions; public Order() { diff --git a/src/main/java/com/labwork1/app/student/model/OrderSession.java b/src/main/java/com/labwork1/app/student/model/OrderSession.java index 3859afa..b76afe6 100644 --- a/src/main/java/com/labwork1/app/student/model/OrderSession.java +++ b/src/main/java/com/labwork1/app/student/model/OrderSession.java @@ -26,11 +26,9 @@ public class OrderSession { public OrderSession(Order order, Session session, Integer count) { 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.count = count; + this.id = new OrderSessionKey(session.getId(), order.getId()); } public OrderSessionKey getId() { diff --git a/src/main/java/com/labwork1/app/student/model/Session.java b/src/main/java/com/labwork1/app/student/model/Session.java index e073d1d..49142aa 100644 --- a/src/main/java/com/labwork1/app/student/model/Session.java +++ b/src/main/java/com/labwork1/app/student/model/Session.java @@ -19,7 +19,7 @@ public class Session { @Column @Temporal(TemporalType.TIMESTAMP) private Timestamp timestamp; - @OneToMany(mappedBy = "session", fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @OneToMany(mappedBy = "session", fetch = FetchType.EAGER) private List orders; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "cinema_fk") diff --git a/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java b/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java index 2eea29e..fe8820d 100644 --- a/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java +++ b/src/main/java/com/labwork1/app/student/repository/CustomerRepository.java @@ -8,8 +8,4 @@ import org.springframework.data.repository.query.Param; import java.util.Optional; public interface CustomerRepository extends JpaRepository { - @Query("delete from Order p where p.customer.id = :id") - Optional deleteCustomerOrders(@Param("id") Long id); - @Query() - void deleteAllCustomers(); } diff --git a/src/main/java/com/labwork1/app/student/repository/CustomerRepositoryExtension.java b/src/main/java/com/labwork1/app/student/repository/CustomerRepositoryExtension.java deleted file mode 100644 index d4dfdeb..0000000 --- a/src/main/java/com/labwork1/app/student/repository/CustomerRepositoryExtension.java +++ /dev/null @@ -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 deleteCustomerOrders(Long id); - void deleteAllCustomers(); -} diff --git a/src/main/java/com/labwork1/app/student/repository/OrderRepository.java b/src/main/java/com/labwork1/app/student/repository/OrderRepository.java index 784f759..7e3c2db 100644 --- a/src/main/java/com/labwork1/app/student/repository/OrderRepository.java +++ b/src/main/java/com/labwork1/app/student/repository/OrderRepository.java @@ -1,24 +1,16 @@ package com.labwork1.app.student.repository; 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.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface OrderRepository extends JpaRepository { - @Query("insert into OrderSession values (orderId, sessionId, count) values (:sessionId, :orderId, :count)") - Order addSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId, - @Param("count") Integer count); - - @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) + @Query("Select os from OrderSession os where os.order.id = :orderId and os.session.id = :sessionId") + OrderSession getOrderSession(@Param("orderId") Long orderId, @Param("sessionId") Long sessionId); + @Modifying + @Query("delete from OrderSession os where os.order.id = :orderId and os.session.id = :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); } \ No newline at end of file diff --git a/src/main/java/com/labwork1/app/student/repository/OrderRepositoryExtension.java b/src/main/java/com/labwork1/app/student/repository/OrderRepositoryExtension.java deleted file mode 100644 index 180b173..0000000 --- a/src/main/java/com/labwork1/app/student/repository/OrderRepositoryExtension.java +++ /dev/null @@ -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 addSession(Long id, Long session, Integer count); - Optional deleteSessionInOrder(Long id, Long session, Integer count); -} diff --git a/src/main/java/com/labwork1/app/student/repository/SessionRepository.java b/src/main/java/com/labwork1/app/student/repository/SessionRepository.java index 6178209..5e27ee1 100644 --- a/src/main/java/com/labwork1/app/student/repository/SessionRepository.java +++ b/src/main/java/com/labwork1/app/student/repository/SessionRepository.java @@ -2,6 +2,11 @@ package com.labwork1.app.student.repository; import com.labwork1.app.student.model.Session; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; -public interface SessionRepository extends JpaRepository, SessionRepositoryExtension { +import java.util.List; + +public interface SessionRepository extends JpaRepository { + @Query("Select s from Session s where s.capacity > 0") + List findAllSessionsWithCapacity(); } diff --git a/src/main/java/com/labwork1/app/student/repository/SessionRepositoryExtension.java b/src/main/java/com/labwork1/app/student/repository/SessionRepositoryExtension.java deleted file mode 100644 index 8dcf3ec..0000000 --- a/src/main/java/com/labwork1/app/student/repository/SessionRepositoryExtension.java +++ /dev/null @@ -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 findAllSessionsWithCapacity(); -} diff --git a/src/main/java/com/labwork1/app/student/repository/impl/CustomerRepositoryImpl.java b/src/main/java/com/labwork1/app/student/repository/impl/CustomerRepositoryImpl.java index 1224e48..ff9bfcf 100644 --- a/src/main/java/com/labwork1/app/student/repository/impl/CustomerRepositoryImpl.java +++ b/src/main/java/com/labwork1/app/student/repository/impl/CustomerRepositoryImpl.java @@ -1,67 +1,63 @@ -package com.labwork1.app.student.repository.impl; - -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.model.Session; -import com.labwork1.app.student.repository.CustomerRepository; -import com.labwork1.app.student.repository.CustomerRepositoryExtension; -import com.labwork1.app.student.repository.OrderRepository; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; - -import java.util.List; -import java.util.Optional; - -public class CustomerRepositoryImpl implements CustomerRepositoryExtension { - @Autowired - @Lazy - private CustomerRepository customerRepository; - @Autowired - @Lazy - private OrderRepository orderRepository; - - @PersistenceContext - private EntityManager em; - - @Override - public Optional deleteCustomerOrders(Long id) { - final Optional currentCustomer = customerRepository.findById(id); - if (currentCustomer.isPresent()) { - final List currentCustomerOrders = currentCustomer.get().getOrders(); - - for (int i = 0; i < currentCustomerOrders.size(); i++) { - final Optional tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId()); - if (tempOrder.isPresent()) { - final Order currentOrder = tempOrder.get(); - List orderSessionList = em - .createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class) - .setParameter("id", id) - .getResultList(); - for (int j = 0; j < orderSessionList.size(); j++) { - final Session currentSession = orderSessionList.get(j).getSession(); - currentOrder.getSessions().remove(orderSessionList.get(j)); - currentSession.getOrders().remove(orderSessionList.get(j)); - em.remove(orderSessionList.get(j)); - em.merge(currentSession); - } - em.merge(currentOrder); - } - } - em.remove(currentCustomer.get()); - } - return currentCustomer; - } - - @Override - public void deleteAllCustomers() { - List customers = em - .createQuery("select c from Customer c", Customer.class) - .getResultList(); - for (var customer : customers) { - deleteCustomerOrders(customer.getId()); - } - } -} +//package com.labwork1.app.student.repository.impl; +// +//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.model.Session; +//import com.labwork1.app.student.repository.CustomerRepository; +//import com.labwork1.app.student.repository.OrderRepository; +//import jakarta.persistence.EntityManager; +//import jakarta.persistence.PersistenceContext; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Lazy; +// +//import java.util.List; +//import java.util.Optional; +// +//public class CustomerRepositoryImpl { +// @Lazy +// private CustomerRepository customerRepository; +// @Lazy +// private OrderRepository orderRepository; +// +// @PersistenceContext +// private EntityManager em; +// +// public Optional deleteCustomerOrders(Long id) { +// final Optional currentCustomer = customerRepository.findById(id); +// if (currentCustomer.isPresent()) { +// final List currentCustomerOrders = currentCustomer.get().getOrders(); +// +// for (int i = 0; i < currentCustomerOrders.size(); i++) { +// final Optional tempOrder = orderRepository.findById(currentCustomerOrders.get(i).getId()); +// if (tempOrder.isPresent()) { +// final Order currentOrder = tempOrder.get(); +// List orderSessionList = em +// .createQuery("select p from OrderSession p where p.id.orderId = :id", OrderSession.class) +// .setParameter("id", id) +// .getResultList(); +// for (int j = 0; j < orderSessionList.size(); j++) { +// final Session currentSession = orderSessionList.get(j).getSession(); +// currentOrder.getSessions().remove(orderSessionList.get(j)); +// currentSession.getOrders().remove(orderSessionList.get(j)); +// em.remove(orderSessionList.get(j)); +// em.merge(currentSession); +// } +// em.merge(currentOrder); +// } +// } +// em.remove(currentCustomer.get()); +// } +// return currentCustomer; +// } +// +// +// public void deleteAllCustomers() { +// List customers = em +// .createQuery("select c from Customer c", Customer.class) +// .getResultList(); +// for (var customer : customers) { +// deleteCustomerOrders(customer.getId()); +// } +// } +//} diff --git a/src/main/java/com/labwork1/app/student/repository/impl/OrderRepositoryImpl.java b/src/main/java/com/labwork1/app/student/repository/impl/OrderRepositoryImpl.java index 51a1f99..5d008e5 100644 --- a/src/main/java/com/labwork1/app/student/repository/impl/OrderRepositoryImpl.java +++ b/src/main/java/com/labwork1/app/student/repository/impl/OrderRepositoryImpl.java @@ -1,105 +1,104 @@ -package com.labwork1.app.student.repository.impl; - -import com.labwork1.app.student.model.*; -import com.labwork1.app.student.repository.CustomerRepository; -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.service.CustomerNotFoundException; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Optional; - -public class OrderRepositoryImpl implements OrderRepositoryExtension { - @Autowired - @Lazy - private CustomerRepository customerRepository; - @Autowired - @Lazy - private OrderRepository orderRepository; - @Autowired - @Lazy - private SessionRepository sessionRepository; - @PersistenceContext - private EntityManager em; - @Override - public Order addOrder(Order order, Long customerId) { - final Optional customer = customerRepository.findById(customerId); - if (customer.isEmpty()) { - throw new CustomerNotFoundException(customerId); - } - order.setCustomer(customer.get()); - em.persist(order); - em.merge(customer.get()); - return order; - } - - @Override - @Transactional - public Optional addSession(Long id, Long session, Integer count) { - if (session <= 0 || count <= 0) { - throw new IllegalArgumentException("addOrder empty fields"); - } - Optional optionalOrder = orderRepository.findById(id); - Optional optionalSession = sessionRepository.findById(session); - if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { - return optionalOrder; - } - final Session currentSession = optionalSession.get(); - final Order currentOrder = optionalOrder.get(); - OrderSession orderSession = em.find(OrderSession.class, - new OrderSessionKey(currentSession.getId(), currentOrder.getId())); - - if (currentSession.getCapacity() < count || - (orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) { - throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s", - currentSession.getCapacity(), count)); - } - if (orderSession == null) - orderSession = new OrderSession(currentOrder, currentSession, count); - else if (orderSession.getCount() + count <= currentSession.getMaxCount()) { - orderSession.setCount(orderSession.getCount() + count); - } - - currentOrder.addSession(orderSession); - currentSession.addOrder(orderSession); - currentSession.setCapacity(currentSession.getCapacity() - count); - em.merge(currentSession); - em.merge(currentOrder); - em.merge(orderSession); - return orderRepository.findById(id); - } - - @Override - public Optional deleteSessionInOrder(Long id, Long session, Integer count) { - final Optional optionalOrder = orderRepository.findById(id); - final Optional optionalSession = sessionRepository.findById(session); - if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { - return optionalOrder; - } - final Order currentOrder = optionalOrder.get(); - final Session currentSession = optionalSession.get(); - - OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id)); - if (orderSession == null) - return optionalOrder; - - if (count >= orderSession.getCount()) { - currentOrder.getSessions().remove(orderSession); - currentSession.getOrders().remove(orderSession); - currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount()); - em.remove(orderSession); - } else { - orderSession.setCount(orderSession.getCount() - count); - currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount()); - em.merge(orderSession); - em.merge(currentSession); - } - - return orderRepository.findById(id); - } -} +//package com.labwork1.app.student.repository.impl; +// +//import com.labwork1.app.student.model.*; +//import com.labwork1.app.student.repository.CustomerRepository; +//import com.labwork1.app.student.repository.OrderRepository; +//import com.labwork1.app.student.repository.SessionRepository; +//import com.labwork1.app.student.service.CustomerNotFoundException; +//import jakarta.persistence.EntityManager; +//import jakarta.persistence.PersistenceContext; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Lazy; +//import org.springframework.transaction.annotation.Transactional; +// +//import java.util.Optional; +// +//public class OrderRepositoryImpl { +// +// @Lazy +// private CustomerRepository customerRepository; +// +// @Lazy +// private OrderRepository orderRepository; +// +// @Lazy +// private SessionRepository sessionRepository; +// @PersistenceContext +// private EntityManager em; +// +// public Order addOrder(Order order, Long customerId) { +// final Optional customer = customerRepository.findById(customerId); +// if (customer.isEmpty()) { +// throw new CustomerNotFoundException(customerId); +// } +// order.setCustomer(customer.get()); +// em.persist(order); +// em.merge(customer.get()); +// return order; +// } +// +// +// @Transactional +// public Optional addSession(Long id, Long session, Integer count) { +// if (session <= 0 || count <= 0) { +// throw new IllegalArgumentException("addOrder empty fields"); +// } +// Optional optionalOrder = orderRepository.findById(id); +// Optional optionalSession = sessionRepository.findById(session); +// if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { +// return optionalOrder; +// } +// final Session currentSession = optionalSession.get(); +// final Order currentOrder = optionalOrder.get(); +// OrderSession orderSession = em.find(OrderSession.class, +// new OrderSessionKey(currentSession.getId(), currentOrder.getId())); +// +// if (currentSession.getCapacity() < count || +// (orderSession != null && orderSession.getCount() + count > currentSession.getMaxCount())) { +// throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s", +// currentSession.getCapacity(), count)); +// } +// if (orderSession == null) +// orderSession = new OrderSession(currentOrder, currentSession, count); +// else if (orderSession.getCount() + count <= currentSession.getMaxCount()) { +// orderSession.setCount(orderSession.getCount() + count); +// } +// +// currentOrder.addSession(orderSession); +// currentSession.addOrder(orderSession); +// currentSession.setCapacity(currentSession.getCapacity() - count); +// em.merge(currentSession); +// em.merge(currentOrder); +// em.merge(orderSession); +// return orderRepository.findById(id); +// } +// +// @Override +// public Optional deleteSessionInOrder(Long id, Long session, Integer count) { +// final Optional optionalOrder = orderRepository.findById(id); +// final Optional optionalSession = sessionRepository.findById(session); +// if (optionalOrder.isEmpty() || optionalSession.isEmpty()) { +// return optionalOrder; +// } +// final Order currentOrder = optionalOrder.get(); +// final Session currentSession = optionalSession.get(); +// +// OrderSession orderSession = em.find(OrderSession.class, new OrderSessionKey(session, id)); +// if (orderSession == null) +// return optionalOrder; +// +// if (count >= orderSession.getCount()) { +// currentOrder.getSessions().remove(orderSession); +// currentSession.getOrders().remove(orderSession); +// currentSession.setCapacity(currentSession.getCapacity() + orderSession.getCount()); +// em.remove(orderSession); +// } else { +// orderSession.setCount(orderSession.getCount() - count); +// currentSession.setCapacity(currentSession.getMaxCount() - orderSession.getCount()); +// em.merge(orderSession); +// em.merge(currentSession); +// } +// +// return orderRepository.findById(id); +// } +//} diff --git a/src/main/java/com/labwork1/app/student/repository/impl/SessionRepositoryImpl.java b/src/main/java/com/labwork1/app/student/repository/impl/SessionRepositoryImpl.java index 5b67c1d..8de629c 100644 --- a/src/main/java/com/labwork1/app/student/repository/impl/SessionRepositoryImpl.java +++ b/src/main/java/com/labwork1/app/student/repository/impl/SessionRepositoryImpl.java @@ -1,74 +1,73 @@ -package com.labwork1.app.student.repository.impl; - -import com.labwork1.app.student.model.Cinema; -import com.labwork1.app.student.model.OrderSession; -import com.labwork1.app.student.model.Session; -import com.labwork1.app.student.repository.CinemaRepository; -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.SessionNotFoundException; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; - -import java.util.List; -import java.util.Optional; - -public class SessionRepositoryImpl implements SessionRepositoryExtension { - @Autowired - @Lazy - private SessionRepository sessionRepository; - @Autowired - @Lazy - private CinemaRepository cinemaRepository; - @PersistenceContext - private EntityManager em; - @Override - public Session addSession(Session session, Long cinemaId) { - if (session == null) return null; - final Optional cinema = cinemaRepository.findById(cinemaId); - if (cinema.isEmpty()) { - throw new CinemaNotFoundException(cinemaId); - } - session.setCinema(cinema.get()); - em.persist(session); - em.merge(cinema.get()); - return session; - } - - @Override - public Session deleteSession(Long id) { - final Optional optionalSession = sessionRepository.findById(id); - if (optionalSession.isEmpty()) { - throw new SessionNotFoundException(id); - } - final Session currentSession = optionalSession.get(); - int size = currentSession.getOrders().size(); - for (int i = 0; i < size; i++) { - OrderSession temp = currentSession.getOrders().get(0); - temp.getSession().removeOrder(temp); - temp.getOrder().removeSession(temp); - em.remove(temp); - } - em.remove(currentSession); - return currentSession; - } - - @Override - public void deleteAllSessions() { - List sessions = em - .createQuery("select s from Session s", Session.class) - .getResultList(); - for (var session : sessions) { - deleteSession(session.getId()); - } - } - - @Override - public List findAllSessionsWithCapacity() { - return em.createQuery("select t from Session t where capacity > 0", Session.class) - .getResultList(); - } -} +//package com.labwork1.app.student.repository.impl; +// +//import com.labwork1.app.student.model.Cinema; +//import com.labwork1.app.student.model.OrderSession; +//import com.labwork1.app.student.model.Session; +//import com.labwork1.app.student.repository.CinemaRepository; +//import com.labwork1.app.student.repository.SessionRepository; +//import com.labwork1.app.student.service.CinemaNotFoundException; +//import com.labwork1.app.student.service.SessionNotFoundException; +//import jakarta.persistence.EntityManager; +//import jakarta.persistence.PersistenceContext; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Lazy; +// +//import java.util.List; +//import java.util.Optional; +// +//public class SessionRepositoryImpl implements SessionRepositoryExtension { +// @Autowired +// @Lazy +// private SessionRepository sessionRepository; +// @Autowired +// @Lazy +// private CinemaRepository cinemaRepository; +// @PersistenceContext +// private EntityManager em; +// @Override +// public Session addSession(Session session, Long cinemaId) { +// if (session == null) return null; +// final Optional cinema = cinemaRepository.findById(cinemaId); +// if (cinema.isEmpty()) { +// throw new CinemaNotFoundException(cinemaId); +// } +// session.setCinema(cinema.get()); +// em.persist(session); +// em.merge(cinema.get()); +// return session; +// } +// +// @Override +// public Session deleteSession(Long id) { +// final Optional optionalSession = sessionRepository.findById(id); +// if (optionalSession.isEmpty()) { +// throw new SessionNotFoundException(id); +// } +// final Session currentSession = optionalSession.get(); +// int size = currentSession.getOrders().size(); +// for (int i = 0; i < size; i++) { +// OrderSession temp = currentSession.getOrders().get(0); +// temp.getSession().removeOrder(temp); +// temp.getOrder().removeSession(temp); +// em.remove(temp); +// } +// em.remove(currentSession); +// return currentSession; +// } +// +// @Override +// public void deleteAllSessions() { +// List sessions = em +// .createQuery("select s from Session s", Session.class) +// .getResultList(); +// for (var session : sessions) { +// deleteSession(session.getId()); +// } +// } +// +// @Override +// public List findAllSessionsWithCapacity() { +// return em.createQuery("select t from Session t where capacity > 0", Session.class) +// .getResultList(); +// } +//} diff --git a/src/main/java/com/labwork1/app/student/service/CustomerService.java b/src/main/java/com/labwork1/app/student/service/CustomerService.java index 9c7cb9e..1deffe5 100644 --- a/src/main/java/com/labwork1/app/student/service/CustomerService.java +++ b/src/main/java/com/labwork1/app/student/service/CustomerService.java @@ -1,6 +1,8 @@ package com.labwork1.app.student.service; 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.util.validation.ValidatorUtil; import org.springframework.stereotype.Service; @@ -12,11 +14,12 @@ import java.util.Optional; @Service public class CustomerService { private final CustomerRepository customerRepository; + private final SessionService sessionService; private final ValidatorUtil validatorUtil; - public CustomerService(CustomerRepository customerRepository, - ValidatorUtil validatorUtil) { + public CustomerService(CustomerRepository customerRepository, SessionService sessionService, ValidatorUtil validatorUtil) { this.customerRepository = customerRepository; + this.sessionService = sessionService; this.validatorUtil = validatorUtil; } @@ -49,12 +52,25 @@ public class CustomerService { @Transactional public Customer deleteCustomer(Long id) { - final Optional customer = customerRepository.deleteCustomerOrders(id); - return customer.orElseThrow(() -> new CustomerNotFoundException(id)); + final Customer customer = findCustomer(id); + // заказы покупателя + final List 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 public void deleteAllCustomers() { - customerRepository.deleteAllCustomers(); + customerRepository.deleteAll(); } } diff --git a/src/main/java/com/labwork1/app/student/service/OrderService.java b/src/main/java/com/labwork1/app/student/service/OrderService.java index 28b243a..ceabb5b 100644 --- a/src/main/java/com/labwork1/app/student/service/OrderService.java +++ b/src/main/java/com/labwork1/app/student/service/OrderService.java @@ -36,29 +36,28 @@ public class OrderService { @Transactional public Order addSession(Long id, Long sessionId, Integer count) { - Optional optionalOrder = orderRepository.findById(id); final Session currentSession = sessionService.findSession(sessionId); - if (optionalOrder.isEmpty()) { - throw new OrderNotFoundException(id); - } - Order currentOrder = optionalOrder.get(); - final Integer countOrderSession = orderRepository.getCountOrderSession(id, sessionId); + final Order currentOrder = findOrder(id); + final OrderSession currentOrderSession = orderRepository.getOrderSession(id, sessionId); + if (currentSession.getCapacity() < count || - (countOrderSession != null && countOrderSession + count > currentSession.getMaxCount())) { - throw new IllegalArgumentException(String.format("No more tickets in sessionId. Capacity: %1$s. Count: %2$s", + (currentOrderSession != null && currentOrderSession.getCount() + count > currentSession.getMaxCount())) { + throw new IllegalArgumentException(String.format("No more tickets in session. Capacity: %1$s. Count: %2$s", currentSession.getCapacity(), count)); } - - if (countOrderSession == null) { + currentSession.setCapacity(currentSession.getCapacity() - count); + /*final Session updatedSession = sessionService.updateSession(currentSession.getId(), + currentSession.getPrice(), currentSession.getCapacity() - count);*/ + if (currentOrderSession == null) { currentOrder.addSession(new OrderSession(currentOrder, currentSession, count)); - return orderRepository.save(currentOrder); } - else if (countOrderSession + count <= currentSession.getMaxCount()) { - orderRepository.delete(currentOrder); - orderRepository.addSession(id, sessionId, countOrderSession + count); + else if (currentOrderSession.getCount() + count <= currentSession.getMaxCount()) { + currentOrder.removeSession(currentOrderSession); + currentOrder.addSession(new OrderSession(currentOrder, currentSession, + currentOrderSession.getCount() + count)); } - return optionalOrder.get(); + return orderRepository.save(currentOrder); } @Transactional(readOnly = true) @@ -75,24 +74,38 @@ public class OrderService { @Transactional public Order deleteOrder(Long 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); return currentOrder; } @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 Session currentSession = sessionService.findSession(session); - Integer countOrderSession = orderRepository.getCountOrderSession(id, session); - if (countOrderSession == null) + final OrderSession currentOrderSession = orderRepository.getOrderSession(id, session); + if (currentOrderSession == null) throw new EntityNotFoundException(); - if (count >= countOrderSession) { - orderRepository.deleteSessionInOrder(id, session); + + if (count >= currentOrderSession.getCount()) { + currentOrder.removeSession(currentOrderSession); sessionService.updateSession(session, currentSession.getPrice(), - currentSession.getCapacity() + countOrderSession); + currentSession.getCapacity() + currentOrderSession.getCount()); } - else - orderRepository.updateSessionInOrder(id, session, count); + else { + currentOrder.removeSession(currentOrderSession); + currentSession.setCapacity(currentSession.getCapacity() + count); + currentOrder.addSession(new OrderSession(currentOrder, currentSession, + currentOrderSession.getCount() - count)); + } + return orderRepository.save(currentOrder); } @Transactional diff --git a/src/main/java/com/labwork1/app/student/service/SessionService.java b/src/main/java/com/labwork1/app/student/service/SessionService.java index b7bde2c..983f525 100644 --- a/src/main/java/com/labwork1/app/student/service/SessionService.java +++ b/src/main/java/com/labwork1/app/student/service/SessionService.java @@ -1,5 +1,6 @@ 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.repository.SessionRepository; import com.labwork1.app.util.validation.ValidatorUtil; @@ -7,24 +8,29 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; +import java.util.Iterator; import java.util.List; import java.util.Optional; @Service public class SessionService { private final SessionRepository sessionRepository; + private final CinemaService cinemaService; private final ValidatorUtil validatorUtil; public SessionService(SessionRepository sessionRepository, - ValidatorUtil validatorUtil) { + CinemaService cinemaService, ValidatorUtil validatorUtil) { this.sessionRepository = sessionRepository; + this.cinemaService = cinemaService; this.validatorUtil = validatorUtil; } @Transactional public Session addSession(Double price, Timestamp date, Long cinemaId, Integer capacity) { final Session session = new Session(price, date, capacity); + final Cinema cinema = cinemaService.findCinema(cinemaId); + session.setCinema(cinema); validatorUtil.validate(session); - return sessionRepository.addSession(session, cinemaId); + return sessionRepository.save(session); } @Transactional(readOnly = true) @@ -42,6 +48,7 @@ public class SessionService { public Session updateSession(Long id, Double price, Integer capacity) { final Session currentSession = findSession(id); currentSession.setPrice(price); + // для обновления полей класса (цены) if (capacity != -1) currentSession.setCapacity(capacity); validatorUtil.validate(currentSession); @@ -50,12 +57,18 @@ public class SessionService { @Transactional 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 public void deleteAllSessions() { - sessionRepository.deleteAllSessions(); + sessionRepository.deleteAll(); } @Transactional diff --git a/src/test/java/com/labwork1/app/JpaCustomerTests.java b/src/test/java/com/labwork1/app/JpaCustomerTests.java index 044c569..5379cdc 100644 --- a/src/test/java/com/labwork1/app/JpaCustomerTests.java +++ b/src/test/java/com/labwork1/app/JpaCustomerTests.java @@ -11,9 +11,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.dao.InvalidDataAccessApiUsageException; import java.sql.Timestamp; +import java.util.List; @SpringBootTest public class JpaCustomerTests { @@ -73,7 +73,7 @@ public class JpaCustomerTests { orderService.addSession(order2.getId(), session2.getId(), 5); Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 5); - Assertions.assertThrows(InvalidDataAccessApiUsageException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> orderService.addSession(order2.getId(), session2.getId(), 6)); // у заказа 1 сеанс @@ -100,22 +100,33 @@ public class JpaCustomerTests { // 3 сеанса всего final Session session3 = sessionService.addSession(300.0, new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10); - // осталось 2 сеанса, у заказа2 0 сеансов - sessionService.deleteSession(session1.getId()); - Assertions.assertEquals(sessionService.findAllSessions().size(), 2); + // удалили заказ2, у которого был сеанс1 + orderService.deleteOrder(order2.getId()); + Assertions.assertEquals(orderService.findAllOrders().size(), 0); + Assertions.assertEquals(sessionService.findAllSessions().size(), 3); - Assertions.assertEquals(orderService - .findOrder(order2.getId()).getSessions().size(), 0); + // создали 3 заказ у 2 покупателя + 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-ой покупатель удален // 0 заказов после его удаления - Assertions.assertEquals(orderService.findAllOrders().size(), 1); + Assertions.assertEquals(sessionService.findSession(session2.getId()).getCapacity(), 8); customerService.deleteCustomer(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(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()); + Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1); + Assertions.assertEquals(sessionService.findAllSessions().size(), 2); } }