hibernate id 生成策略 annotation @GeneratedValue

方法很简单,只需要在id属性上添加@GeneratedValue的注释即可,如下:
@Entity
public class Teacher {
//private TeacherPK pk;
private int id;
private String name;

@Id
@GeneratedValue//////////默认使用的是AUTO类型,还有TABLE,IDENTITY(使用于sql server,mysql数据库中,oracle不适用),SEQUENCE类型(oracle使用该种),通过@GeneratedValue(strategy=GenerationType.IDENTITY)配置
public int getId() {
return id;
}
}
-------
当使用SEQUENCES的时候可以使用自定义的SEQUENCES生成器的名字,只需要在类名上加上注释:@SequenceGenerator(name="teacherSEQ", sequenceName="teacherSEQ_DB")
import java.util.Date;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.IdClass;
import javax.persistence.SequenceGenerator;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@SequenceGenerator(name="teacherSEQ", sequenceName="teacherSEQ_DB")
public class Teacher {
//private TeacherPK pk;
private int id;
private String name;
private String title;
private String yourWifeName;
private Date birthDate;
private boolean good;
private Gender gender;

@Enumerated(EnumType.STRING)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public boolean isGood() {
return good;
}
public void setGood(boolean good) {
this.good = good;
}
@Transient
public String getYourWifeName() {
return yourWifeName;
}
public void setYourWifeName(String yourWifeName) {
this.yourWifeName = yourWifeName;
}
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="Teacher_GEN")////使用TableGenerator自动生成id的方式
//////还可以写成 @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="teacherSEQ")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Temporal(TemporalType.TIME)
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}

你可能感兴趣的:(annotation,GeneratedValue)