[Hibernate Annotations] 主鍵映射
1.簡(jiǎn)單主鍵:
使用 @Id 注解可以將實(shí)體bean中的某個(gè)屬性定義為標(biāo)識(shí)字段.使用 @GeneratedValue 注解可以定義標(biāo)識(shí)字段的生成策略:
AUTO - 可以是identity類型的字段,或者sequence類型或者table類型,取決于不同的底層數(shù)據(jù)庫(kù).
TABLE - 使用表保存id值
IDENTITY - identity字段
SEQUENCE - sequence
2.組合主鍵:
定義組合主鍵的幾種語(yǔ)法:
使用 @Id 注解可以將實(shí)體bean中的某個(gè)屬性定義為標(biāo)識(shí)字段.使用 @GeneratedValue 注解可以定義標(biāo)識(shí)字段的生成策略:
AUTO - 可以是identity類型的字段,或者sequence類型或者table類型,取決于不同的底層數(shù)據(jù)庫(kù).
TABLE - 使用表保存id值
IDENTITY - identity字段
SEQUENCE - sequence
@Id?@GeneratedValue(strategy
=
GenerationType.IDENTITY)
public ?Long?getId()?{?
?}
public ?Long?getId()?{?

2.組合主鍵:
定義組合主鍵的幾種語(yǔ)法:
- 將組件類注解為@Embeddable,并將組件的屬性注解為@Id
- 將組件的屬性注解為@EmbeddedId
- 將類注解為@IdClass,并將該實(shí)體中所有屬于主鍵的屬性都注解為@Id
@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
}
@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帛羅閣 閱讀(2550) 評(píng)論(0) 編輯 收藏 所屬分類: 開源軟件