hibernate how to make a database automatically created time (timestamp)
My own project needs to have a function, that is, every time the user changes the data in the database, I want the database to automatically record the time of the change, I used the database is Microsoft SQL Server. The first thing I did was set the type of the column as a timestamp (timestamp) in the database, but I found that if I did, I would have an error hibernate execution, that is, the property column set to the timestamp (timestamp) type would be wrong.
When I read someone's tutorial on the internet, I said that you can add annotations to the column in the Po class in Hibernate (Hibernate to support annotation mapping (annotation) at the start of version 3.2. If you are using the Post version 3.2, you can refer to the blog in this link to enable the annotation function, add in the PO class Add annotations as follows:
@Column (name = "Update_time", length =)
@Temporal (temporaltype.timestamp)
@Generated ( Generationtime.insert) Public
Date Getupdatetime () {return
this.updatetime;
}
However, after I run to find that can not solve my problem, or will be an error, then I want to change the way. Since the Java class in the hibernate can not be resolved, then I go to the database to look at it.
Later, I found the solution to change the column type from timestamp to datetime in the database, and set it to GETDATE () in the default value or binding, as shown in the following illustration:
At this point, note that the notes in the PO can not be deleted, otherwise it will be an error. Therefore, in the retention of the PO class annotation in the premise, and then to the database to modify the property column, you can achieve the effect of automatic update time. As follows:
Commentdao.inserttocomment ("005", "001", "Well written", "0001");
I use the DAO class to insert a piece of information, notice. At this point I did not pass the Update property to the value. After running, the effect in the database remains as follows:
As you can see, the time it automatically saves is accurate to the millisecond level.