数据的插入和更新时间

最近项目要求某些表记录数据的插入时间和更新时间:

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Wangwang {
    private Integer id;
   private User owner;
   private boolean deleted;
    
    private Date createdTime = new Date();
    private Date updatedTime;

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne
    public User getOwner() {
        return owner;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }

    @Column(nullable = false)
    public boolean isDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

    @Column(updatable=false)
    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    @Column(columnDefinition="TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", updatable=false)
    public Date getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(Date updatedTime) {
        this.updatedTime = updatedTime;
    }

}

 createdTime记录插入数据的时间,updatedTime记录更新数据的时间。要注意@Column注解的updatable=false,否则更新数据时,时间戳会先被MySQL修改为当前时间,然后Hibernate的更新语句会把时间改回原来的值。

 

利用MySQL的触发器也可实现此功能: http://lanhuidong.iteye.com/blog/765134

你可能感兴趣的:(mysql,Hibernate,Blog)