代码之家  ›  专栏  ›  技术社区  ›  Blackjack

在javaspring引导中减少另一个表中列的值

  •  0
  • Blackjack  · 技术社区  · 7 年前

    我为应用程序构建了后端进程,使用 弹簧靴,maven 我有3个域(客户、产品、订单),这是表的列。

            A. Customer:  1. id,
                          2. name,
                          3. address,
                          4. email,
                          5. phone.
    
            B. Product :  1. id,
                          2. name,
                          3. stock,
                          4. price.
    
            C. Order   :  1. id,
                          2. customer_id,
                          3. product_id,
                          4. quantity.
    

    秩序 product.stock 和……一样多 order.quantity .

    我应该如何处理我的代码才能做到这一点?

    这是我的 订单.java

    package com.learn.ecommerce.domain;
    
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    
    import javax.persistence.*;
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotNull;
    import java.io.Serializable;
    import java.util.Objects;
    
    /**
     * A order model.
     */
    @Entity
    @Table(name = "orders")
    public class Order extends AbstractAuditingEntity implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @ManyToOne
    @JsonIgnoreProperties("")
    private Customer customer;
    
    @ManyToOne
    @JsonIgnoreProperties("")
    private Product product;
    
    @NotNull
    @Min(0)
    @Column(nullable = false)
    private Integer quantity;
    
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public Customer getCustomer() {
        return customer;
    }
    
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    
    public Product getProduct() {
        return product;
    }
    
    public void setProduct(Product product) {
        this.product = product;
    }
    
    public Integer getQuantity() {
        return quantity;
    }
    
    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
    
        if (o == null || getClass() != o.getClass())
            return false;
    
        Order order = (Order) o;
    
        return !(order.getId() == null || getId() == null) && Objects.equals(getId(), order.getId());
    }
    
    @Override
    public int hashCode() {
        return Objects.hashCode(getId());
    }
    
    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", customer=" + customer +
                ", product=" + product +
                ", quantity=" + quantity +
                '}';
    }
    

    这是我的

    package com.kevin.ecommerce.service.impl;
    
    import com.kevin.ecommerce.domain.Order;
    import com.kevin.ecommerce.repository.OrderRepository;
    import com.kevin.ecommerce.service.OrderService;
    import com.kevin.ecommerce.service.dto.OrderDTO;
    import com.kevin.ecommerce.service.mapper.OrderMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    
    @Slf4j
    @Service
    @Transactional
    public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    /**
     * Save a order
     *
     * @param orderDTO the entity to save
     * @return the persisted entity
     */
    @Override
    public OrderDTO save(OrderDTO orderDTO) {
        log.debug("Request to save Order : {}", orderDTO);
        Order order = OrderMapper.INSTANCE.toEntity(orderDTO);
        order = orderRepository.save(order);
        return OrderMapper.INSTANCE.toDto(order);
    }
    
    /**
     * Get all of orders
     *
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public List<OrderDTO> findAll() {
        log.debug("Request to get all Orders");
        return orderRepository.findAll().stream()
                .map(OrderMapper.INSTANCE::toDto)
                .collect(Collectors.toCollection(LinkedList::new));
    }
    
    /**
     * Get specific order
     *
     * @param id the id of entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<OrderDTO> findOne(Long id) {
        log.debug("Request get Order : {}", id);
        return orderRepository.findById(id)
                .map(OrderMapper.INSTANCE::toDto);
    }
    
    /**
     * Delete specific order
     *
     * @param id the id of entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete Order : {}", id);
        orderRepository.deleteById(id);
    }
    
    /**
     * Get all of orders by page
     * @param pageable
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Page<OrderDTO> findAll(Pageable pageable) {
        log.debug("pageable");
        return orderRepository.findAll(pageable).map(OrderMapper.INSTANCE::toDto);
    }
    

    }

    OrderRepository.java文件

    package com.nostratech.ecommerce.repository;
    
    import com.nostratech.ecommerce.domain.Order;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface OrderRepository extends JpaRepository<Order, Long> {
    }
    

    产品存储库.java

    package com.nostratech.ecommerce.repository;
    
    import com.nostratech.ecommerce.domain.Product;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface ProductRepository extends JpaRepository<Product, Long> {
    }
    

    public OrderDTO save ,但我是java后端的新手,不知道该怎么做。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gerben Jongerius    7 年前

    public OrderDTO save(OrderDTO orderDTO) {
       log.debug("Request to save Order : {}", orderDTO);
       Product purchased = productRepository.findById(orderDTO.getProduct().getId());
       Order order = OrderMapper.INSTANCE.toEntity(orderDTO);
       Objects.requireNonNull(purchased, "You cannot buy a non existing product");
    
       // now prevent Hibernate from creating a new product in the database (and the user from manipulating the product)
       order.setProduct(purchased);
       purchased.setStock(purchased.getStock() - order.getQuantity());
    
       // this save operation will also trigger the product to be saved (cascading), but it is cleaner to explicitly trigger a save operation.
       order = orderRepository.save(order);
       productRepository.save(purchased);
       return OrderMapper.INSTANCE.toDto(order);
    }