一.数据的删除
方法1.从“多”的一方进行数据的删除
books.hbm.xml文件不变:
<many-to-one name="publishers" column="publisherId" class="com.entry.Publishers" lazy="false" cascade="save-update"/>
publishers.hbm.xml文件:
<set name="books" lazy="false" cascade="all" inverse="true"> <!-- cascade="save-update" 也可以 --> <key column="publisherId" not-null="true"/> <one-to-many class="com.entry.Books"/> </set>
在MyHibernateDao.java中添加如下代码:
public Books getBook(int Id){ Books book = null; Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); book = (Books)session.get(Books.class, new Integer(Id)); tran.commit(); return book; } public void deleteBook(Books book){ Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); session.delete(book); tran.commit(); }
在HibernateServlet.java中添加如下代码
Books book1 = dao.getBook(3); book1.getPublishers().getBooks().remove(book1); book1.setPublishers(null); dao.deleteBook(book1);
注意如果没有book1.getPublishers().getBooks().remove(book1); book1.setPublishers(null);这两句,会出现 org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)这个异常,主要是因为Books和Publishers二者的级联关系。
所以我们可以先将级联断开,然后再进行删除“多”的一方。
方法2.从“一”的这一方进行删除,这样的话就是和“一”这一方相关联的“多”的一方都会被删除
在HibernateServlet.java中添加如下代码:
Publishers publisher = dao.getPublisher(1);
dao.deletePublisher(publisher);
publishers.hbm.xml 和 books.hbm.xml 不用改变
在MyHibernateDao.java中添加如下代码:
public Publishers getPublisher(int Id){ Publishers publisher = null; Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); publisher = (Publishers)session.get(Publishers.class, new Integer(Id)); tran.commit(); return publisher; } public void deletePublisher(Publishers publisher){ Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); session.delete(publisher); tran.commit(); }
原文:http://www.cnblogs.com/hujunzheng/p/4620968.html