0 Replies Latest reply on Sep 12, 2006 8:16 PM by Vasu Chou

    em.remove() has problem if version is maintained by db

    Vasu Chou Newbie

      Though I posted this issue before let me rephrase again with some example. Lets say Customer and Order has one to many relationship. Assume Customer C1 has 2 Orders O1 and O2. In Customer entity I defined collection of Orders and annotated it as OneToMany. In Orders I defined Customer and annotated it as ManyToOne and JoinColumn. So code looks something like this

      In Customer

      
      private List<Orders> orderList = new ArrayList<Orders>();
      
      @OneToMany(mappedBy="customer", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
      public List<Orders> getOrderList()
      {
       return orderList;
      }
      
      @Version
      @Column(name="Version", insertable=false, updatable=false)
      public int getVersion()
      {
       return version;
      }
      


      In Order

      
      private Customers customer;
      @ManyToOne()
      @JoinColumn(name="CustomerID")
      public Customers getCustomer()
      {
       return customer;
      }
      
      @Version
      @Column(name="Version", insertable=false, updatable=false)
      public int getVersion()
      {
       return version;
      }
      
      


      As it is clear from the code that we have version field but we allow hibernate to use version for validation but updation of it is done through database trigger.

      Now when I call em.remove(customer) i got an exception :
      StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

      When i dig into this issue I found out that when I call em.remove(customer), em first calls update on Customer and then delete of all child(Order in this case) and then parent (Customers). But since update gets called before delete which makes Version number of Customer record is incremented by 1 in database through db trigger. This makes deletion fails due to version conflict.

      Any help will be really appreciated.

      Thnx
      V