Java – get the wrong timestamp from the object saved to the database by hibernate
I am new to hibernate and am developing a web project using it
I have an object named area, which has a date object (Java. SQL. Timestamp) attribute modifieddate When I create a new object, modifiedate is null, and then I send it to gethibernatetemplate() saveOrUpdate(area); In my own class, I extended org springframework. orm. hibernate3. support. Hibernate daosupport, which uses the current timestamp settings and saves them in the database In the database, it will be saved as date and time
My problem is that in most cases, when updating an object with a date of 1 millisecond compared to the date saved in the database, this will cause this exception. If you try to update anything without reloading the page:
an org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
When getting objects from subsequent databases, there is no problem with the correct date. It will get the wrong value only when it is created
Is there any way to get the correct modified date in saveOrUpdate?
If mapping is required, use < timestamp name = "modifieddate" column = "modifieddate" / > and all tests run on localhost, all on the same machine
I already have a solution by calling gethibernatetemplate() refresh(area); After saveOrUpdate, I got the correct timestamp, but I still wonder if there is a way to get the correct modified date in saveOrUpdate
Solution
My theory:
What happens is that the data type you use on the database side is more accurate than that on the Java side, so during the generation of database specific SQL, the values persisted to the database will lose precision (or rounded in some way, see below) Here is how to determine:
>Remember, hibernate works by generating SQL statements that execute in the database In order to diagnose such hibernate mapping problems, you need to view the executing SQL to accurately understand what is happening. > Turn on the 'show SQL' setting for hibernation This will cause hibernate to dump the original SQL being executed on the database. > Check the log in the test It will help to implement toString on the class and record the value to compare with SQL hibernate generated for insert Does the value in the SQL statement match the value of the Java timestamp field?
You should check the precision setting of the datetime type of the database For example, on SQL server, datetime implements millisecond rounding (see the 'accuracy' field), which effectively leads to the loss of accuracy of millisecond values Depending on your precision requirements, you will need to change the Java type to which the column is mapped or the type of column in the database