本文转载自http://esffor.iteye.com/blog/168242
通过在表中及POJO中增加一个Timestamp字段来表示记录的最后更新时间,来达到多用户同时更改一条数据的冲突,这个timestamp由数据库自动添加,无需人工干预
数据库结构:
create
table studentTimestamp(id
varchar(
32),name
varchar(
32),lastUpdateDateTime
timestamp
not
null
default
current_timestamp
on
update
current_timestamp);
pojos:
package Timestamp;
import java.util.Date;
public
class Student {
private String id;
private String name;
private Date lastUpdateDateTime;
public String getId() {
return id;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
public Date getLastUpdateDateTime() {
return lastUpdateDateTime;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
public
void setLastUpdateDateTime(Date lastUpdateDateTime) {
this.lastUpdateDateTime = lastUpdateDateTime;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
public
void setId(String id) {
this.id = id;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
public String getName() {
return name;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
public
void setName(String name) {
this.name = name;
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
}
![](https://i-blog.csdnimg.cn/blog_migrate/0196c3df5ea9e936f21e9932cca91014.gif)
}
Student.hbm.xml
<?
xml version="1.0" encoding="utf-8"
?>
<!
DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<
hibernate-mapping
>
<
class
name
="Timestamp.Student"
table
="studentTimestamp"
>
<
id
name
="id"
unsaved-value
="null"
>
<
generator
class
="uuid.hex"
></
generator
>
</
id
>
<!--
timestamp标签必须跟在id标签后面
-->
<
timestamp
name
="lastUpdateDateTime"
column
="lastUpdateDateTime"
></
timestamp
>
<
property
name
="name"
type
="string"
column
="name"
></
property
>
</
class
>
</
hibernate-mapping
>
Hibernate.cfg.xml
测试代码:
测试结果:
Hibernate: insert into studentTimestamp (lastUpdateDateTime, name, id) values (?, ?, ?)
Hibernate: select student0_.id as id0_, student0_.lastUpdateDateTime as lastUpda2_0_, student0_.name as name0_ from studentTimestamp student0_ where student0_.name='tom11'
Hibernate: select student0_.id as id0_, student0_.lastUpdateDateTime as lastUpda2_0_, student0_.name as name0_ from studentTimestamp student0_ where student0_.name='tom11'
v1=2007-12-12 16:30:53.0--v2=2007-12-12 16:30:53.0
Hibernate: update studentTimestamp set lastUpdateDateTime=?, name=? where id=? and lastUpdateDateTime=?
Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect):
v1=2007-12-12 16:30:54.844--v2=2007-12-12 16:30:53.0
Hibernate: update studentTimestamp set lastUpdateDateTime=?, name=? where id=? and lastUpdateDateTime=?