问题描述
我试用了在我的应用程序中的域类的休眠映射,它是Book,Author和Publisher.I想删除一个没有Books的Publisher或Author。所以,我编写了添加/删除Book的逻辑如下。
删除一本书会检查作者和发布者中的图书集的大小。如果他们只包含单个图书实例(将要删除的),那么作者和Publisher被删除。不要将这本书从他们的Book集中删除。在我的程序中,我把用于检查Set和删除Author之前的大小的代码块发布者,如片段所示。
当我删除作者的所有书籍时,作者被成功删除。但删除发布者导致StaleStateException。
实际的错误追溯在最后给出。
现在,作为最后一项工作,我交换了删除Publisher和Author的代码块,并将deletePublisher(publisher)放在包含deleteAuthor(作者)。现在,出版商被删除,但删除作者导致StaleStateException。
我无法弄清楚我的逻辑是否有问题。在我的GenericDao.delete(Object obj)方法中,异常发生在transaction.commit()和回滚发生之前。我还列出了Dao实现代码的相关部分。
如果有人可以帮忙,请告诉我如何解决这个错误。
谢谢
标记
公共类书籍{
private Long book_id;
私人字符串名称;
私人作者作者;
私人发布商发布商;
...
}
公共类作者{
private长author_id;
私人字符串名称;
私人设置< Book>图书;
public Author(){
super();
books = new HashSet< Book>();
}
...
}
public class Publisher {
private Long publisher_id;
私人字符串名称;
私人设置< Book>图书;
public Publisher(){
super();
books = new HashSet< Book>();
}
...
}
Book.hbm.xml中有
<多对一名称=publisherclass =Publishercolumn = PUBLISHER_IDlazy =falsecascade =save-update/>
Author.hbm.xml
...
< key column =AUTHOR_ID/>
<一对多课程=Book/>
< / set>
Publisher.hbm.xml
<$ p $ < code>< set name =booksinverse =truetable =BOOKlazy =falseorder-by =BOOK_NAME asccascade =delete-orphan>
< key column =PUBLISHER_ID/>
<一对多课程=Book/>
< / set>
创建图书将图书实例添加到作者和发布者的集合中。
doPost(HttpServletRequest请求,HttpServletResponse响应){
...
Book book = new Book();
...
Publisher publisher = createPublisherFromUserInput();
作者author = createAuthorFromUserInput();
...
publisher.getBooks()。add(book);
author.getBooks()。add(book);
bookdao.saveOrUpdateBook(book);
$ / code>
删除一本书
doPost(HttpServletRequest请求,HttpServletResponse响应){
...
Book bk = bookdao.findBookById(bookId);
Publisher pub = bk.getPublisher();
作者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);
$ b $ Da $实现
public class PublisherDao extends GenericDao {
@Override
public void deletePublisher(Publisher publisher){
String name = publisher.getName() ;
logger.info(delete pub =+ name)之前;
delete(publisher);
logger.info(deleted pub =+ name);
公共抽象类GenericDaoImpl {
@Override
public void delete(Object obj ){
SessionFactory factory = HibernateUtil.getSessionFactory();
会话会话= factory.openSession();
Transaction tx = null;
尝试{
tx = session.beginTransaction();
session.delete(obj);
logger.info(after session.delete(obj));
logger.info(delete():before tx.commit); //直到这里没有例外
tx.commit();
} catch(HibernateException e){
if(tx!= null){
tx.rollback();
logger.info(delete():txn回滚); //所有书籍都被删除时发生这种情况
}
throw e;
} finally {
session.close();
}
}
}
是来自tomcat的跟踪
SEVERE:servlet的servlet.service()deletebookservlet抛出异常
org.hibernate.StaleStateException :批量更新从update [0]返回了意外的行数;实际行数:0;预期: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)
解决方案这是因为你在DAO方法中开始和结束事务,这不是一个好的选择,你应该使用声明式事务作为 that cascade =delete-orphan
意味着 cascade =delete
。)之后,您提交了交易,即作者和图书已被删除。尽管你的Publisher实例仍然有一个对已经被删除的Book的引用,它有陈旧的状态。因此,当您尝试删除发布服务器并再次级联Book时,将会出现StaleStateException。在较高级别的应用程序中管理交易会阻止这种情况发生,因为作者,发布者和预订都将在同一交易中被删除。
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.
这篇关于StaleStateException,而通过休眠删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!