首页 > Web开发 > 详细

Hibernate的数据删除,更改

时间:2015-07-04 19:44:56      阅读:221      评论:0      收藏:0      [点我收藏+]

一.数据的删除

方法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();
    }

 

Hibernate的数据删除,更改

原文:http://www.cnblogs.com/hujunzheng/p/4620968.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!