现在有如下一个实体类:
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id")
private long id; // 学生id
@Column(name = "name")
private String name; //学生姓名
@Column(name = "sex")
char sex; // 性别
@Column(name = "age")
int age; // 年龄
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Studnet{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
可以看到,我们将将生成程略设置为了TABLE:
@GeneratedValue(strategy = GenerationType.TABLE)
那个数据库java程序会再创建一个表来维护Student实体类对应表的主键的自增,不需要底层数据库支持自增。
hibernate_sequences记录了下一个id值:
从打印的sql语句中也可以看出:
Hibernate: drop table if exists hibernate_sequences
Hibernate: drop table if exists student
Hibernate: create table hibernate_sequences (sequence_name varchar(255) not null, next_val bigint, primary key (sequence_name))
Hibernate: create table student (id bigint not null, age integer, name varchar(255), sex char(1), primary key (id))
Hibernate: select tbl.next_val from hibernate_sequences tbl where tbl.sequence_name=? for update
Hibernate: insert into hibernate_sequences (sequence_name, next_val) values (?,?)
Hibernate: update hibernate_sequences set next_val=? where next_val=? and sequence_name=?
Hibernate: insert into student (age, name, sex, id) values (?, ?, ?, ?)