@CreationTimestamp和@UpdateTimestamp

时间:2016-10-03 19:09:16

标签: hibernate jpa annotations

这是我的博客课程

@Entity
@Component 
@Table
public class Blog implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;
@Id
private String id;
private String name;
private String Description;

@CreationTimestamp
private Date createdOn;

@UpdateTimestamp
private Date updatedOn;

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return Description;
}
public void setDescription(String description) {
    Description = description;

}
public Date getCreatedOn() {
    return createdOn;
}
public void setCreatedOn(Date createdOn) {
    this.createdOn = createdOn;
}
public Date getUpdatedOn() {
    return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
    this.updatedOn = updatedOn;
}


}
创建新博客时,

创建时间戳createdOn和updatedOn成功存储,但当更新现有博客时,更新updatedOn字段,而createdOn字段变为空。我希望createdOn字段保留创建它的时间戳。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:9)

将updateable = false注释添加到您不想更新的字段。

以下是createddate(仅可插入)和modifieddate(可插入/可更新)的示例代码

@Column(name = "CreatedDate", updatable=false)
@CreationTimestamp
private Timestamp createdDate;

@Column(name = "ModifiedDate")
@UpdateTimestamp
private Timestamp modifiedDate;