1. 程式人生 > >解決org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)

解決org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)

相關程式碼:
===============================================
public class VoteQuestion {
    private Set options = new HashSet();
    。。。

 /**
  * @hibernate.set cascade = "all" table = "VOTE_OPTION" inverse =
  *                "true" lazy = "true" order-by = "id"
  *
  * @hibernate.collection-one-to-many class =
  *                                   "eorg.etoken.pojo.VoteOption"
  *
  * @hibernate.collection-key column = "QUESTION_ID"
  */
 public Set getOptions() {
        return options;
 }

}

public class VoteOption {
    private VoteQuestion question;
    。。。。

 /**
  * @hibernate.many-to-one class = "eorg.etoken.pojo.VoteQuestion" cascade =
  *                        "none" not-null = "true" column = "QUESTION_ID"
  *                        update = "false"
  */
 public VoteQuestion getQuestion() {
       return question;
 }

}

public class VoteServiceImpl{
 。。。
 public void deleteVoteOption(int optionId) {
      Transaction tx = session.beginTransaction();
      VoteOption option = (VoteOption) session.load(VoteOption.class, new Long(optionId));
      session.delete(option);
      tx.commit();
 }
}

===============================================

當呼叫VoteServiceImpl的deleteVoteOption方法時,就會丟擲下列Exception:
org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)

原因是votequestion與voteoption有連帶關係,不能直接刪除voteoption,而應該從votequestion裡remove voteoption!

因此上面的deleteVoteOption方法只需要修改一行即可,見下面程式碼

===============================================
 public void deleteVoteOption(int optionId) {
      Transaction tx = session.beginTransaction();
      VoteOption option = (VoteOption) session.load(VoteOption.class, new Long(optionId));
      option.getQuestion().getOptions().remove(option);
      tx.commit();
 }
===============================================