实体中有一些熟悉是唯一的,他们不是主键,可能是手机号也可能是身份证号等,这时候我们就可以通过索引来约束这些数据的唯一性
举例,用户身份证号为唯一的,所以我们可以在实体类中这样写
package cm.demo.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Table(name="c_auth", indexes= {@Index(name="identity_index", columnList="_identity", unique=true)})
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Auth {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="_id", nullable=false, columnDefinition="int comment 'id'")
private int id;
@OneToOne(targetEntity=User.class)
@JoinColumn(name="_user_id", columnDefinition="int comment '用户id'", nullable=false)
private User user;
@Column(name="_realname", columnDefinition="varchar(20) comment '真实姓名'", nullable=false)
private String realname;
@Column(name="_identity", columnDefinition="varchar(18) comment '身份证号'", nullable=false)
private String identity;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="_time", nullable=false)
private Date time; //创建时间
public Auth(User user, String realname, String identity, Date time) {
this.user = user;
this.realname = realname;
this.identity = identity;
this.time = time;
}
}
其中
@Table(name="c_auth", indexes= {@Index(name="identity_index", columnList="_identity", unique=true)})
indexes部分就是我们设置索引的地方,@Index是一个具体的索引信息,其中name为索引名,columnList对应数据库的属性名,我这里需要把身份证号设为索引故用“_identity”(身份证),unique为true——不能一样:true(很好理解吧)
由此生成的数据表索引部分这样的
image.png
网友评论