0

我有一个非常简单的单向@OneToMany,从父对象到 CascadeType.ALL 的子对象列表。我将如何正确删除和删除其中一个孩子?

简单地调用 List 上的 remove(child) 然后 session.saveOrUpdate(parent) 当然不起作用,并且除非我指定孤儿删除,否则不会在数据库中删除子项。

作为孤立删除的替代方法,如果我 session.delete(child) 在数据库中删除它,然后从列表中删除(child) 然后我必须 session.refresh(parent) 所以我的父对象是否正确在内存中有正确的状态吗?

我将如何正确删除孩子并将其从数据库中删除而不进行孤立删除?

我目前正在我的 ParentDao 中考虑这个问题:

public void removeChild(Parent parent, Child child) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
        session.beginTransaction();

        session.delete(child);

        session.getTransaction().commit();

        parent.getChildren().remove(child);
        session.refresh(parent);
    } catch (RuntimeException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        session.close();
    }
}
4

2 回答 2

2

当您打算手动执行 @Cascade(DELETE_ORPHAN) (来自 Hibernate)时,这里是执行几乎相同行为的代码。

实体:

class Library {

  @Id
  private Integer id;

  @OneToMany
  private List<Book> books;

  // getters and setters    
}

class Book {

  @Id
  private Integer id; 

  @ManyToOne
  private Libraby library;

  // getters and setters
}

还有一个简单的例子:

session.beginTransaction();

// load a library with ID = 1
Library library = session.get(Library.class, 1);

// assuming that your library has two books
Book book = library.getBooks().get(0); //gets the first book
library.getBooks().remove(0); // Remove this book from the library
session.delete(book);

session.getTransaction().commit();

并且您的 Book 将从数据库中删除,并且父级的 lisf 也将被更新。

于 2014-10-23T16:21:41.360 回答
0

你可以试试下面的代码吗?在提交之前从列表中删除。

public void removeChild(Parent parent, Child child) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
        session.beginTransaction();

        parent.getChildren().remove(child); 
        session.delete(child);

        session.getTransaction().commit();


       // session.refresh(parent); // this is not required
    } catch (RuntimeException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        session.close();
    }
}
于 2014-10-23T17:49:59.637 回答