在Hibernate中无法删除没有子节点的父节点

时间:2017-01-12 22:57:04

标签: java hibernate jpa

我有两个对象用户工作订单。一个用户可以拥有多个工单。问题是,当我删除用户时,它还会删除分配给该用户的工单。在删除用户之前,我尝试将我的工作订单外键设置为NULL,但它仍然删除了与该用户相关的所有工作订单。我想删除用户而不删除分配给用户的工单。我错过了什么或做错了什么?

这是我的用户类:

   @OneToMany(fetch = FetchType.LAZY, mappedBy="user", orphanRemoval=true)
   private Set<WorkOrder> workOrder;

WorkOrder类:

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id", nullable = true)
    private User user;

UserDAOImpl类:

    @Override
    public void deleteUser(int theId) {
        // get the current hibernate session

        Session currentSession = sessionFactory.getCurrentSession();

        // delete object with primary key

        User user = currentSession.get(User.class, theId);  
        Set workorders = user.getWorkOrder();


        Iterator<WorkOrder> work = workorders.iterator();
        while (work.hasNext()){

            WorkOrder workorder = work.next();
            workorder.setUser(null); 
            }   

        currentSession.remove(user);
    }

1 个答案:

答案 0 :(得分:0)

删除'orphanRemoval = true'并检查Workorder.user上没有'cascade'(如果关系是双向的)