hibernate id 生成策略 annotation @GeneratedValue

引用地址 : http://blog.sina.com.cn/s/blog_80e498b10100vjcc.html

 

方法很简单,只需要在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;
 } 
}

--------------------------- 下面是自己项目中的代码----------------

@Id
@Column(name = "RESOURCE_ID")
@SequenceGenerator(name = "SIS_RESOURCE", sequenceName = "SEQ_SIS_RESOURCE_ID")
@GeneratedValue(generator = "SIS_RESOURCE", strategy = GenerationType.SEQUENCE)
public long getResource_id() {
return resource_id;

@Column(name = "CZR")
public String getCzr() {
return czr;
}

posted @ 2012-11-20 09:42  不经意的回眸  阅读(341)  评论(0编辑  收藏  举报