首先創建一個BaseModel,自動生成創建時間和更新時間
@SuppressWarnings("serial")
@MappedSuperclass
public class BaseModel implements Serializable{
@Temporal(TemporalType.TIMESTAMP)
@Column(insertable=false, updatable=false)
@CreationTimestamp
protected Date createTime;
@JsonIgnore
@Temporal(TemporalType.TIMESTAMP)
@Column(insertable=false)
@UpdateTimestamp
protected Date lastUpdateTime;
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
}
然后創建一個RandomIdModel,利用org.hibernate.id.UUIDHexGenerator生成的uuid作為主鍵
@SuppressWarnings("serial")
@MappedSuperclass
public class RandomIdModel extends BaseModel {
@Id
@Column(length=32)
@GeneratedValue(generator="UUIDHexGenerator")
@GenericGenerator(name="UUIDHexGenerator", strategy="uuid")
protected String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
然后就可以創建其他的具體實體類繼承上面的model了,這樣就保證了所有的表都會有創建時間和更新時間了
@SuppressWarnings("serial")
@Entity
@Table(name="tb_user",
indexes={ @Index(name=User.UK_NAME, unique=true, columnList="name"),
@Index(name=User.UK_PHONE, unique=true, columnList="phone")})
public class User extends RandomIdModel{
public static final String UK_NAME = "uk_name";
public static final String UK_PHONE = "uk_phone";
@Column(length=24)
private String name;
@Column(length=32)
private String password;
@Temporal(TemporalType.TIMESTAMP)
private Date birth;
@Enumerated(EnumType.STRING)
@Column(length=8)
private Sex sex;
@Column(length=64)
private String email;
@Column(length=11)
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
創建唯一索引時,自定義索引名,有利於后續業務判斷。
當插入數據不唯一時,可根據拋出的異常,明確知道是哪個字段違反約束導致的
if(e.getCause() instanceof ConstraintViolationException){ String constraintName = ((ConstraintViolationException)e.getCause()).getConstraintName(); if(constraintName.equals(User.UK_NAME)){ return Resp.error(Resp.ErrorCode.USER_NAME_EXITS, null); } if(constraintName.equals(User.UK_PHONE)){ return Resp.error(Resp.ErrorCode.USER_PHONE_EXITS, null); } }
