Dev@Free

zJun's Tech Weblog

[Hibernate Annotations] 主键映射

1.简单主键:
使用
@Id 注解可以将实体bean中的某个属性定义为标识字段.使用 @GeneratedValue 注解可以定义标识字段的生成策略:

AUTO - 可以是identity类型的字段,或者sequence类型或者table类型,取决于不同的底层数据库.
TABLE - 使用表保存id值
IDENTITY - identity字段
SEQUENCE - sequence

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
public  Long getId() {  }

2.组合主键:

定义组合主键的几种语法:
  • 将组件类注解为@Embeddable,并将组件的属性注解为@Id
  • 将组件的属性注解为@EmbeddedId
  • 将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id
使用 @IdClass 组合来定义组合主键类 , 对应了一个实体类中的多个字段或属性, 而且主键类中用于定义主键的字段或属性和实体类中对应的字段或属性在类型上必须一致.

@Entity
@IdClass(FootballerPk.
class //  指明主键类
public   class  Footballer {
// part of the id key
@Id  public  String getFirstname() {
return  firstname;
}

public   void  setFirstname(String firstname) {
this .firstname  =  firstname;
}

// part of the id key
@Id  public  String getLastname() {
return  lastname;
}

public   void  setLastname(String lastname) {
this .lastname  =  lastname;
}

public  String getClub() {
return  club;
}

public   void  setClub(String club) {
this .club  =  club;
}

// appropriate equals() and hashCode() implementation
}

@Embeddable  
//  主键类
public   class  FootballerPk  implements  Serializable {
// same name and type as in Footballer
public  String getFirstname() {
return  firstname;
}

public   void  setFirstname(String firstname) {
this .firstname  =  firstname;
}

// same name and type as in Footballer
public  String getLastname() {
return  lastname;
}

public   void  setLastname(String lastname) {
this .lastname  =  lastname;
}

// appropriate equals() and hashCode() implementation
}


posted on 2007-03-07 15:49 zJun's帛罗阁 阅读(2530) 评论(0)  编辑  收藏 所属分类: 开源软件


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2007年3月>
25262728123
45678910
11121314151617
18192021222324
25262728293031
1234567

统计

常用链接

留言簿(15)

随笔分类

随笔档案

相册

收藏夹

博客

文档

站点

论坛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜