从数据库中删除 table OrderItem

Delete table OrderItem from Database

可以开始了: 我在 Spring 做药学项目。我正在使用 Eclipse 和数据库 PostgreSQL。

在数据库中,我有 table 名称:OrderItem、CustomerOrder、Product 和 Register(这是 class,带有用户的通行证和信息)。

好的,我想删除给定 ID 的 CustomerOrder。

co.deleteCustomerOrder(co.getCustomerOrder(id));

如果我这样做,我会遇到这样的错误:

详情: Key(orderid)=(1421007984736) 已调用 table "orderItem" 错误:修改或删除 table "customerorder" 违反了外键“fk60163f61b0099af4” table “orderitem”

所以我把这个放在第一位

 cos.deleteOrderItem(cos.getOrderItem(id)) 

然后

co.deleteCustomerOrder(co.getCustomerOrder(id));

现在我有这样的错误:

HTTP 状态 500 - 请求处理失败;嵌套异常是 java.lang.IllegalArgumentException:尝试使用空实体创建删除事件

也许某些实体有问题 classes: 注册或 other.By 当我用 PgAdminIII orderItem 删除时的方式然后当然我没有得到第一个错误,我可以完成这行代码

   co.deleteCustomerOrder(co.getCustomerOrder(id));

正常。

****如何解决第二个错误?。我不想使用 PgAdmin xD****

我的一些代码。

package app.Spring.domain;



import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "CustomerOrder")
public class CustomerOrder {

        @Id
        @Column(name = "orderID")
        private long orderID;

        @ManyToOne(cascade = { CascadeType.MERGE })
        private Register register;

        @Column(name = "status")
        private String status;

        @Column(name = "totalCost")
        private float totalCost;

        @Column(name = "orderDate")
        private Date orderDate;

        public CustomerOrder() {
        }

        public CustomerOrder(long orderID, Register register, String status,
                        float totalCost, Date orderDate) {
                this.orderID = orderID;
                this.register = register;
                this.status = status;
                this.totalCost = totalCost;
                this.orderDate = orderDate;
        }

        public long getOrderID() {
                return orderID;
        }

        public void setOrderID(long orderID) {
                this.orderID = orderID;
        }

        public Register getRegister() {
                return register;
        }

        public void setRegister(Register register) {
                this.register = register;
        }

        public String getStatus() {
                return status;
        }

        public void setStatus(String status) {
                this.status = status;
        }

        public float getTotalCost() {
                return totalCost;
        }

        public void setTotalCost(float totalCost) {
                this.totalCost = totalCost;
        }

        public Date getOrderDate() {
                return orderDate;
        }

        public void setOrderDate(Date orderDate) {
                this.orderDate = orderDate;
        }
}



package app.Spring.domain;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "OrderItem")
public class OrderItem {

        @Id
        @Column(name = "itemID")
        private long itemID;


        @ManyToOne(cascade = { CascadeType.MERGE })
        private Product product;

        @ManyToOne(cascade = { CascadeType.MERGE })
        private CustomerOrder customerOrder;

        @Column(name = "quantity")
        private int quantity;

        public OrderItem() {
        }

        public OrderItem(long itemID, Product product, CustomerOrder customerOrder,
                        int quantity) {
                this.itemID = itemID;
                this.product = product;
                this.customerOrder = customerOrder;
                this.quantity = quantity;
        }

        public long getItemID() {
                return itemID;
        }

        public void setItemID(long itemID) {
                this.itemID = itemID;
        }

        public Product getProduct() {
                return product;
        }

        public void setProduct(Product product) {
                this.product = product;
        }

        public CustomerOrder getCustomerOrder() {
                return customerOrder;
        }

        public void setCustomerOrder(CustomerOrder customerOrder) {
                this.customerOrder = customerOrder;
        }

        public long getQuantity() {
                return quantity;
        }

        public void setQuantity(int quantity) {
                this.quantity = quantity;
        }
}

控制器

@Controller
@RequestMapping("/admin/users")
public class AdminController {

    @Autowired
    LocalValidatorFactoryBean validator;

    @Autowired
    RegisterService reg;

    @Autowired    
CustomerOrderService co;
    @Autowired
OrderItemService cos;     

 @RequestMapping("/removecustomer/{id}")
    public String removeCustomerOrderById(@PathVariable Long id) {

        System.out.println("remove  customerOrderID "+id);
      cos.deleteOrderItem(cos.getOrderItem(id));
    co.deleteCustomerOrder(co.getCustomerOrder(id));


        return "redirect:/";
    }
}

客户订单服务

public class CustomerOrderImpl implements CustomerOrderService{


    protected final Logger log = LoggerFactory.getLogger(getClass());

    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }    

  @Override
      public CustomerOrder getCustomerOrder(Long id) {
          return (CustomerOrder)sessionFactory.getCurrentSession().get(CustomerOrder.class.getName(), id);
      }

 public void deleteCustomerOrder(CustomerOrder v) {
            sessionFactory.getCurrentSession().delete(v);
            sessionFactory.getCurrentSession().flush();
        }


}

订单服务

public class OrderItemImpl implements OrderItemService {



    protected final Logger log = LoggerFactory.getLogger(getClass());

    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }    



    public OrderItem getOrderItem(Long id) {
        return (OrderItem)sessionFactory.getCurrentSession().get(OrderItem.class.getName(), id);

    }
public void deleteOrderItem(OrderItem v) {
            sessionFactory.getCurrentSession().delete(v);
            sessionFactory.getCurrentSession().flush();
        }
}
cos.deleteOrderItem(cos.getOrderItem(id));
co.deleteCustomerOrder(co.getCustomerOrder(id));

table 中的每条记录(行)都有一个键。您正在使用同一个密钥删除两个不同 table 中的项目。

除非他们碰巧处于一对一的关系中,否则记录的 id 不反映这种关系。在这种情况下,您正在尝试使用未记录的密钥删除订单项。

说白了:

  • 您要删除客户订单 16;

  • 您无法删除客户订单 16;因为它有 orderItems 4 & 5 由于外键而与之相关。

  • 您正在尝试删除订单项目 16;不存在(第二个错误)。

正确的解决方案是:

  • 设置从 customerOrder 和 orderItems 的关系级联删除 (cascade = {CascadeType.DELETE, CascadeType.MERGE})

  • 在删除customerOrder之前,找到相关的orderItems删除(同样,不同元素的key不会有关联)

如果您在理解键、外键和级联的概念时遇到问题,您应该首先详细了解 SQL 的工作原理。

问题已解决:)

更改删除和更改一些代码以查找相关的方法 orderItems.Ty 为您解答我应该了解更多 SQL.This CascadeType.Remove 不需要。

public void deleteOrderItem2(OrderItem orderItem) throws Exception {
      Session session=null;
      Transaction tx=null;
      try {
            session =     sessionFactory.openSession();
              tx=session.beginTransaction();
              orderItem = (OrderItem) session.merge(orderItem);
              session.delete(orderItem);
              session.flush();
              tx.commit();
      } catch (PersistenceException pe) {
              tx.rollback();
              throw pe;
      } finally {
              session.close();
      }

}