Hibernate: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

77,945

Solution 1

I faced the same problem, it was combination of spring and hibernate. After breaking my head for 3-4 hours, I just randomly checked my column related to version. As I was using an old table where I recently introduced the version column, and didn't default to zero - so it has added null for all the rows and the row which I was trying to delete as well. So just as a guess I entered 0, and magically it worked on next run. I hope that helps.

Solution 2

If I understand correctly, you're trying to add an existing Institution, with the ID 2, to a new CreationDate. Since the Institution already exists, you shouldn't create a new one. You should simply get it from the Hibernate Session:

Institution institution = (Institution) session.load(Institution.class, 2);
creationDate.addInstitution(institution);

Solution 3

Check you model object which is going to be updated. Basically You should check your 'Not null' values; like already defined and primary key etc. This will help.

Share:
77,945
user1798755
Author by

user1798755

Updated on April 11, 2021

Comments

  • user1798755
    user1798755 about 3 years

    First of all sorry. I know it's have been alot of same topics, but maybe my english bad or maybe I did not find the right answer.

    I use Optimistic locking @Version annotation. I need one for one Row from one table have numerous Rows from different table and I did insert like this:

    So it has to look like this:

    Institution (This is a one of the row of my table(Institution))

           - CreationDate A (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)
    
           - CreationDate B (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)
    
           - CreationDate C (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)
    

    So, to put this CreationDate in diferent variation i decide to put id manually for particular Institution to which I want to add my CreationDate.

    My main method class:

    CreationDate crdate = new CreationDate();   
    Institution inst= new Institution();
    Set<Institution> instituset = new HashSet<Institution>();
    
    ***inst.setInstitutionId(2);***
    
    inst.setNameOfInstitution("MyInstitution");
    inst.setTypeName("Education");
    instituset.add(inst);
    

    The line which mark with stars i do add in my code when I want to attach to my Institution another row of data After first insert my Version Row in Database changed to one.

    Here my Institution entity:

    @Entity
    @Table(name="INSTITUTION")
    public class Institution implements Serializable{
    
    
        private static final long serialVersionUID = -7636394097858726922L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="INSTITUTION_ID")
        private int institutionId;
    
    
        @Version
        @Column(name="VERSION")
        private int version;
    
    
        @Column(name="NAME_INSTITUTION")
        private String nameOfInstitution;
    
        @Column(name="TYPE_NAME")
        private String typeName;
    
    
        @ManyToMany(mappedBy="institution", fetch = FetchType.LAZY)
        @Cascade(org.hibernate.annotations.CascadeType.ALL)
        private Set<CreationDate> creationDate = new HashSet<CreationDate>();
    
        //getter and setter methods ommited
    
        public String toString() {
            return institutionId + " , " + nameOfInstitution + " , " + typeName 
        }       
    }
    

    And my CreatioDate entity:

    @Entity
    @Table(name="CREATION_DATE")
    public class CreationDate implements Serializable {
    
    
        private static final long serialVersionUID = 1648102358397071136L;
    
        @Id
        @GeneratedValue(strategy=IDENTITY)
        @Column(name="DATE_ID")
        private int dateId;
    
    
        @Column(name="PARTICULAR_DATE")
        private Date particularDate;
    
        @Version
        @Column(name="VERSION")
        private int version;
    
        @Temporal(TemporalType.DATE)
        @Column(name="CHILD_GO_SCHOOL_DATE")
        private Date childGoSchoolDate;
    
        @Temporal(TemporalType.DATE)
        @Column(name="CHILD_ADMISSION_DATE")
        private Date childAdmissionDate;
    
    
        @ManyToMany(fetch = FetchType.LAZY)
        @Cascade(org.hibernate.annotations.CascadeType.ALL)
        @JoinTable(name="CREATIONDATE_INSTITUTION", 
                                        joinColumns=@JoinColumn(name="DATE_ID"), 
                        inverseJoinColumns=@JoinColumn(name="INSTITUTION_ID"))
        private Set<Institution> institution = new HashSet<Institution>();
    
        @OneToMany(fetch=FetchType.EAGER, orphanRemoval=true)
        @Cascade(org.hibernate.annotations.CascadeType.ALL)
        @JoinTable(name="SRC_DATE", joinColumns=@JoinColumn(name="DATE_ID"),
                        inverseJoinColumns=@JoinColumn(name="SRC_ID"))
        private List<ScheduleRotationChild> scheduleRotationChild = new ArrayList<ScheduleRotationChild>();
    
    
            //getter and setter methods ommited
    
    
        public String toString() {
    
            return  dateId + " , " 
                + particularDate + " , " 
                + childGoSchoolDate + " , " 
                + childAdmissionDate + "  " + scheduleRotationChild ;
    
        }
    }
    

    My dao:

    public CreationDate insertData(CreationDate creationdate) {
            sessionFactory.getCurrentSession().saveOrUpdate(creationdate);
            log.info(creationdate.getDateId());
            return creationdate;
    
        }
    

    So the exception occurs when I try to insert my data to my Institution the secont time.

     Hibernate: insert into CREATION_DATE (CHILD_ADMISSION_DATE,
     CHILD_GO_SCHOOL_DATE, PARTICULAR_DATE, VERSION) values (?, ?, ?, ?)
    
     Hibernate: insert into SCHEDULE_ROTATION_CHILD (CHILD_ADMITTED,
     CHILD_GO_SCHOOL, CHILD_UNDER_3_YEARSOLD, CHILD_UPPER_3_YEARSOLD,
     DAY_SCHEDULE, NUMBER_OF_CHILD, ROTATION, VERSION, WORK_SCHEDULE)
     values (?, ?, ?, ?, ?, ?, ?, ?, ?)
    
     Hibernate: update INSTITUTION set
     NAME_INSTITUTION=?, TYPE_NAME=?, VERSION=? where INSTITUTION_ID=? and
     VERSION=? Exception in thread "main"
    
    org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException:
         Object of class [edu.demidov.dom.Institution] with identifier [2]:
         optimistic locking failed; nested exception is
         org.hibernate.StaleObjectStateException: Row was updated or deleted by
        another transaction (or unsaved-value mapping was incorrect):
         [edu.demidov.dom.Institution#2]
    
  • user1798755
    user1798755 about 11 years
    Hello sir.. Nice to see you again you are my programming grace. Thank you for you precious answers. Sir, I'm trying to add the CreationDate to a existing Institution which ID of Institution is 2 in database. The first inserting take action with out problem but second with error. But also consider my DAO code I do not declare any Transactions, but it's anyway do Transaction???. Thank you so much for your help.
  • JB Nizet
    JB Nizet about 11 years
    Yes, that's what my answer shows you how to do. transactions should be started in the service layer, not in the DAO layer.
  • user1798755
    user1798755 about 11 years
    Oh I didn't know it that transaction should be started in service layer, I'm new in this technologies. To much things do not know. I'm sorry for this not appropriate questions. But maybe you point me on right direction to good article how to extract data using two parameters for extracting, cuz I can't figure out this also.. Like I want to extract data corresponding with particular name and particular date at one query. Is it not would be so bad manner behave here and to you?? Thank you.
  • JB Nizet
    JB Nizet about 11 years
    The best reference is a good book, or the official documentation: docs.jboss.org/hibernate/core/3.6/reference/en-US/html_singl‌​e
  • Vedran Kopanja
    Vedran Kopanja almost 8 years
    I also lost around 3 hours, and this was the problem for me, one version column was null. Thanks!
  • Yuming Cao
    Yuming Cao about 4 years
    I'm having a similar issue when deleting an entity with column named "errors", it carries serialized json string. When the column is null, delete works fine. But when it carries non null value, it throws the aforementioned exception. Still trying to figure out the root cause. Any help would be appreciated.
  • 0TTT0
    0TTT0 over 3 years
    I had forgotten to pass in 'id' as a hidden value to my form, so it was being set to the default of 0 which does not exist in the db so this exception was being thrown on attempted hibernate update.