第一种方法:使用@IdClass
下面是定义一个主键类:
- public class CustomerPK implements Serializable {
- private String name;
- private Long ssn;
- public CustomerPK() {
- }
- ...
- @Override
- public int hashCode() {
- ...
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- ...
- return true;
- }
- }
public class CustomerPK implements Serializable {
private String name;
private Long ssn;
public CustomerPK() {
}
...
@Override
public int hashCode() {
...
return result;
}
@Override
public boolean equals(Object obj) {
...
return true;
}
}
主键类要满足一下要求:
必须可序列化(其中之一对泛型BaseDAO设计有点方便)
必须具备共有的无参构造函数
必须实现hashCode和equals方法
现在在Customer类必须具有CustomerPK类所具有的成员属性,并且这些成员属性都要标注@Id注释
- @IdClass(CustomerPK.class)
- @<SPAN class=hilite2>Entity</SPAN>
- public class Customer {
- @Id
- private String name;
- @Id
- private Long ssn;
- private String address;
- ...
- }
@IdClass(CustomerPK.class)
@Entity
public class Customer {
@Id
private String name;
@Id
private Long ssn;
private String address;
...
}
第二种方法: 使用@EmbeddedId,是把主键代码嵌入到bean class中
有两种方法把主键类的成员属性映射到表中的字段,一种是在主键类的源代码中指定@Column映射
另一种是使用@AttributesOverrides。
1:
- @Embeddable
- public class CustomerPK implements Serializable {
- @Column(name="NAME")
- private String name;
- @Column(name="SSN")
- private Long ssn;
- ...
- @<SPAN class=hilite2>Entity</SPAN>
- public class Customer {
- private String address;
- @EmbeddedId
- private CustomerPK pk;
- ...
@Embeddable
public class CustomerPK implements Serializable {
@Column(name="NAME")
private String name;
@Column(name="SSN")
private Long ssn;
...
@Entity
public class Customer {
private String address;
@EmbeddedId
private CustomerPK pk;
...
2:
- @Embeddable
- public class CustomerPK implements Serializable {
- private String name;
- private Long ssn;
- ...
- @<SPAN class=hilite2>Entity</SPAN>
- public class Customer {
- private String address;
- @EmbeddedId
- @AttributeOverrides({
- @AttributeOverride(name="name",column=@Column(name="NAME")),
- @AttributeOverride(name="ssn",column=@Column(name="SSN"))
- })
- private CustomerPK pk;
- ...