简体   繁体   中英

Can't delete parent without a child in Hibernate

I have two objects User and Workorder . One user can have multiple work orders. The problem is when I delete user it also deletes assigned work orders to that user. I have tried to set my work orders foreign keys to NULL before deleting the user but it still deletes all the associated work orders with that user. I'd like to delete user without deleting the work order assigned to user. What am I missing or doing wrong?

Here's is my User class:

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

WorkOrder class:

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

UserDAOImpl class:

    @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);
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM