Object receives invalid timestamp from Hibernate stored in database

I am new to Hibernate and am working on a web project that uses it.

I have an object called a scope that has a date ( java.sql.Timestamp ) modifiedDate attribute. When I create a new modifieDate object it is null and after sending it to getHibernateTemplate().saveOrUpdate(area); in my own class, which extends org.springframework.orm.hibernate3.support.HibernateDaoSupport , it is set with the current timestamp and stored in the database. It is saved as a datetime in the database.

My problem in most cases, when an object is updated with a date equal to 1 millisecond, compared with the fact that it is stored as in a database, this leads to this exception if something tries to update without reloading the page:

 an org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) 

There is no problem with the correct date when you subsequently retrieve the object from the database, only when it is created it gets the wrong value.

Is there a way to get the correct modifiedDate in SaveOrUpdate?

If necessary, a mapping is used that uses <timestamp name="modifiedDate" column="ModifiedDate"/> , and all tests are run on the local host with all running on the same machine.

I already have work by calling getHibernateTemplate().refresh(area); right after saveOrUpdate, I get the correct timestamp, but I still would like to know if there is a way to get the correct change in the saveOrUpdate file.

+7
source share
1 answer

My theory:

What happens is that you use a less accurate data type on the database side than on the Java side, so the values ​​that you save in the database lose accuracy (or are rounded somehow, see below) during database generation-specific SQL Here, how to say for sure:

  • Remember that Hibernate works by creating SQL statements that execute in your database. To diagnose problems with Hibernate mappings like this, you will need to see how SQL is executed to know exactly what is going on.

  • Enable the 'show SQL' option for Hibernate. This will cause Hibernate to dump raw SQL running in the database.

  • Examine the logs from your tests. This will help to implement toString in your class and register a value for comparison with the sleeping SQL generator for INSERT . Values ​​in SQL statements match Java timestamp field value?

You should check the accuracy settings for your DATETIME database. For example, on SQL Server, DATETIME implements millisecond rounding (see the "Precision" field), which actually results in a loss of precision for millisecond values. You will want to change the type of Java into which the column is mapped, or change the type of column in the database, depending on your needs.

+4
source

All Articles