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
-
将类注解为@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
}