欢迎加入JPA讨论群:234134357
JPA的生命周期时间可以分为4类:持久化,更新,删除和加载。在系统中我们便可以利用回调函数触发指定事件执行特定操作,例如需要区分对象是否为新建。如下:
@Component
@Scope("prototype")
@Entity(name = "_User")
public class User implements Serializable{
private static final long serialVersionUID = 1417900800633538392L;
// 业务属性
private String name, phoneticCode;
private String loginName, password;
// 数据持久相关的辅助属性
private String id;
private Date createdTime;
private int objectVersion;
@Id
@Column(length = 40)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length = 30, nullable = false, unique = true)
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@Column(length = 30, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 拼音码
*
* @return
*/
@Column(length = 20)
public String getPhoneticCode() {
return phoneticCode;
}
public void setPhoneticCode(String phoneticCode) {
this.phoneticCode = phoneticCode;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
@Version
public int getObjectVersion() {
return objectVersion;
}
public void setObjectVersion(int objectVersion) {
this.objectVersion = objectVersion;
}
/**
* 使用回调函数验证以及创建默认必要属性
*/
@PrePersist
@PreUpdate
public void dataCompleted() {
if (StringUtil.isEmpty(id)) {
setId(UUID.randomUUID().toString());
}
if (null == getCreatedTime()) {
setCreatedTime(new Date());
}
setPhoneticCode(PinYinTool.getPinYinCode(name));
}
}
我们将id的 创建时间等赋值操作交给回调函数处理,该函数只有在持久或更新之前才会被调用所以我们可以通过实体是否具有id来区分对象是否属于新建