开发者

StaleStateException while deleting through hibernate

I tried out hibernate mapping for domain classes in my application- which are Book,Author and Publisher.I wanted to remove a Publisher or Author who has no Books.So,I coded the logic for adding/deleting a Book as below.

Deleting a book checks the size of Set of Books in Author and Publisher.If they contain only the single book instance(which is going to be deleted) ,the Author and Publisher are deleted.Else the book is removed from their Sets of Book.

In my program,I put the codeblock for checking size of Set and deleting Author before that of Publisher as shown in the snippet.

When I delete all books of an author,the author gets removed successfully.But the delete publisher causes a StaleStateException. The actual error traceback is given at the end.. Now , as a last effort,I interchanged the code blocks which delete Publisher and Author,and put the deletePublisher(publisher) before the block containing deleteAuthor(author).Now ,the Publisher gets deleted but deleting Author causes StaleStateException.

I could n't figure out if there was some problem in my logic.Tried logging and found that in my GenericDao.delete(Object obj) method,the exception happens just before transaction.commit() and rollback occurs.I have also listed the relevant parts of Dao implementation code.

If anyone can help..please tell me how I can solve this error.

thanks

mark

public class Book {
    private Long book_id;   
    private String name;
    private Author author;
    private Publisher publisher;
        ...
}

public class Author {
    private Long author_id;
    private String name;
    private Set<Book> books;

    public Author() {
        super();
        books = new HashSet<Book>();
    }
        ...
}
public class Publisher {
    private Long publisher_id;
    private String name;
    private Set<Book> books;
    public Publisher() {
        super();
        books = new HashSet<Book>();

    }
       ...
}

Book.hbm.xml has

<many-to-one name="publisher" class="Publisher" column="PUBLISHER_ID" lazy="false" cascade="save-update"/>
<many-to-one name="author" class="Author" column="AUTHOR_ID" lazy="false" cascade="save-update"/>

Author.hbm.xml

...
<set name="books" inverse="true" table="BOOK" lazy="false" order-by="BOOK_NAME asc" cascade="delete-orphan">
            <key column="AUTHOR_ID" />
            <one-to-many class="Book" />
</set>

Publisher.hbm.xml

<set name="books" inverse="true" table="BOOK" lazy="false" order-by="BOOK_NAME asc" cascade="delete-orphan">
            <key column="PUBLISHER_ID" />
            <one-to-many class="Book" />
</set>

Creating a Book adds the book instance to the Sets in Author and Publisher.

doPost(HttpServletRequest request, HttpServletResponse response){
   ...
   Book book = new Book();
   ...
   Publisher publisher = createPublisherFromUserInput();
   Author author = createAuthorFromUserInput();
   ...
   publisher.getBooks().add(book);
   author.getBooks().add(book);
   bookdao.saveOrUpdateBook(book);
}

Deleting a book

 doPost(HttpServletRequest request, HttpServletResponse response){
      ...
      Book bk = bookdao.findBookById(bookId);
       Publisher pub = bk.getPublisher();
       Author author = bk.getAuthor();
       if (author.getBooks().size()==1){
        authordao.deleteAuthor(author);

        }else{
          author.getBooks().remove(bk);

        }
       if(pub.getBooks().size()==1){
            publisherdao.deletePublisher(pub);

        }else{
              pub.getBooks().remove(bk);

        }
        bookdao.deleteBook(bk);

    }

Dao implementations

public class PublisherDao extends GenericDao{
   @Override
    public void deletePublisher(Publisher publisher) {
        String name = publisher.getName();
        logger.info("before delete pub="+name);
        delete(publisher);
        logger.info("deleted pub="+name);

    }
        ...
}

public abstract class GenericDaoImpl{       
   @Override
    public void delete(Object obj) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.delete(obj);
            logger.info("after session.delete(obj)");
            logger.info("delete():before tx.commit");//till here no exception
            tx.commit();
        } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
            logger.info("delete():txn rolled back");//this happens when all Books are deleted
        }
            throw e;
        } finally {
            session.close();
        }

    }
开发者_如何学编程}

And here is the trace from tomcat

SEVERE: Servlet.service() for servlet deletebookservlet threw exception
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at 

...
org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(ExpectationImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at bookstore.dao.GenericDao.delete(Unknown Source)
    at bookstore.dao.PublisherDao.deletePublisher(Unknown Source)
    at bookstore.servlets.MyBookDeleteServlet.doPost(Unknown Source)


It's because you're beginning and ending transactions in your DAO methods. That's not a good choice. You should use declarative transactions as provided by Spring or some other framework. What's happening is that when you delete the Author, the Book is deleted as well. (While I don't believe it's explicitly mentioned in the Hibernate docs, you can see in the source code that cascade="delete-orphan" implies cascade="delete".) After that, you commit the transaction, meaning that both Author and Book have been deleted. Your Publisher instance, though, still has a reference to the Book which has been deleted--i.e. it has stale state. Therefore, when you attempt to delete the Publisher and, by cascade, the Book again, you get the StaleStateException. Managing your transactions at a higher level of your app would prevent this, as the Author, Publisher, and Book would all be deleted in the same transaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜