public class User {
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
在如上类中假设需要定义一个联合主键 id,name,在hibernate中利用注解映射方法有如下三种:
1、将组件类注解为@Embeddable,并将实体类中组件的注解为@Id
首先需要抽象出一个组件类,并将其注解为可嵌入式的Embeddedable在User中进行引用
@Embeddable
public class UserPk implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
其次要在实体类中将组件属性注解为@ID
@Entity
public class User {
private UserPk userPk;
private String address;
@Id
public UserPk getUserPk() {
return userPk;
}
public String getAddress() {
return address;
}
public void setUserPk(UserPk userPk) {
this.userPk = userPk;
}
public void setAddress(String address) {
this.address = address;
}
}
2、将组件的属性注解为@EmbeddedId
首先需要抽象出一个组件类,在User中进行引用
public class UserPk implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
其次需要在实体类中对组件属性注解为嵌入式的ID,即:@EmbeddedId
@Entity
public class User {
private UserPk userPk;
private String address;
@EmbeddedId
public UserPk getUserPk() {
return userPk;
}
public String getAddress() {
return address;
}
public void setUserPk(UserPk userPk) {
this.userPk = userPk;
}
public void setAddress(String address) {
this.address = address;
}
}
3、将类注解为@IdClass,并将该实体中所有属于主键属性都注解为@Id
抽象出组件类
public class UserPk implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
实体类
@Entity
@IdClass(value = UserPk.class)
public class User {
private int id;
private String name;
private String address;
@Id
public int getId() {
return id;
}
@Id
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}