Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6176139
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T00:02:48+00:00 2026-05-24T00:02:48+00:00

I tried out hibernate mapping for domain classes in my application- which are Book,Author

  • 0

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)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T00:02:49+00:00Added an answer on May 24, 2026 at 12:02 am

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Has anyone tried out working with the Delete and update command of SPDataSource used
I have two classes binded mapped with Hibernate and I can't figure out the
Can someone please help me to figure out how to create domain classes for
I tried to use the xslt task in Ant to modify a Hibernate mapping
I have an application using hibernate 3.1 and JPA annotations. It has a few
Have someone tried out DeCAL in Delphi 2009? I'm thinking about upgrading from 2007,
I downloaded today Subsonic 3 and tried out the examples. I am having a
I have more than one OpenID as I have tried out numerous. As people
I am very interested in streaming data for web-applications. I have tried out some
I have been recently digging into Mobile Programming, I practically tried out the J2ME

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.