下面是定义组合主键的几种语法:
- 将组件类注解为@Embeddable,并将组件的属性注解为@Id(不常用)
- 将组件的属性注解为@EmbeddedId
- 将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id(个人喜欢这种和第二种)
这种方法需要主键类一般主键类命名方式采用..._pkpackage wife; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.IdClass; @Entity @IdClass(value=Wife_pk.class) public class Wife { private int id; private String name; private int age; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @Id public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
- 下面有个主键类的例子,注意:主键类一定要实现serializable接口
package wife; import java.io.Serializable; public class Wife_pk implements Serializable{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { // TODO Auto-generated method stub return super.hashCode(); } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); } }