@Id注解可以将实体bean中的摸个属性定义为表示符,该属性可以通过应用自身进行设置,也可通过Hibernate生成(推荐),使用@GeneratedValue注解可以定义该标识的生成策略:
.AUTO
.TABLE
.IDENTITY
.SEQUENCE
package com.woxiaoe.study.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
private int id;
private int age;
private String name;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)//@GeneratedValue默认为AUTO
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
*
create table Student (
id integer not null auto_increment,
name varchar(255),
age integer not null,
primary key (id)
)
*/
TableGenerator(要注意pkColumnName,valueColumnName 的值不能为数据库关键字)
@Entity @TableGenerator( name="TB_GEN", table = "GENERATOR_TABLE", pkColumnName="pKey", valueColumnName = "pId", pkColumnValue = "id", allocationSize=20//增长量 ) public class Student { private int id; private int age; private String name; @Id @GeneratedValue(strategy=GenerationType.TABLE,generator = "TB_GEN") public int getId() { return id; } …………
基于主键生成器
@Entity public class Student { private BigInteger id; private int age; private String name; @Id //@GeneratedValue(strategy=GenerationType.TABLE,generator = "TB_GEN") @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid") @GenericGenerator(name = "java5_uuid", strategy = "com.woxiaoe.study.hibernate.util.UUIDGenerator")//自定义的生成策略 @Column(name = "id", precision = 65, scale = 0)//定义字段长度 public BigInteger getId() { return id; }