联合主键

来源:互联网 发布:熊族刀路软件英文原版 编辑:程序博客网 时间:2024/05/17 00:58
两个或多个字段组成的主键,我们叫联合主键。在面向对象中,我们用JPA怎么定义这种情况呢?怎么定义联合主键?用面向对象的思想来思考的话,联合主键里的复合主键(字段),可以把它看成一个整体,然后采用一个主键类来描述这个复合主键的字段。

关于联合主键类,大家一定要遵守以下几点JPA规范:
  1. 必须提供一个public的无参数构造函数。
  2. 必须实现序列化接口。
  3. 必须重写hashCode()和equals()这两个方法。这两个方法应该采用复合主键的字段作为判断这个对象是否相等的。
  4. 联合主键类的类名结尾一般要加上PK两个字母代表一个主键类,不是要求而是一种命名风格。
AirLinePK.java:

@Embeddable
//这个注解代表ArtLinePK这个类是用在实体里面,告诉JPA的实现产品:在实体类里面只是使用这个类定义的属性。
//简单的理解为:ArtLinePK里的属性可以看成是ArtLine类里的属性,好比ArtLinePK的属性就是在ArtLine里定义的
public class AirLinePK implements Serializable{
@Column(length=3)
private String startCity;
@Column(length=3)
private String endCity;
public String getStartCity() {
return startCity;
}
public void setStartCity(String startCity) {
this.startCity = startCity;
}
public String getEndCity() {
return endCity;
}
public void setEndCity(String endCity) {
this.endCity = endCity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((endCity == null) ? 0 : endCity.hashCode());
result = prime * result
+ ((startCity == null) ? 0 : startCity.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AirLinePK other = (AirLinePK) obj;
if (endCity == null) {
if (other.endCity != null)
return false;
} else if (!endCity.equals(other.endCity))
return false;
if (startCity == null) {
if (other.startCity != null)
return false;
} else if (!startCity.equals(other.startCity))
return false;
return true;
}
}


@Entity
public class AirLine {
@EmbeddedId
//这个注解用于标注id这个属性为实体的标识符,因为我们使用的是复合主键类,所以我们要用@EmbeddedId这个专门针对复合主键类的标志实体标识符的注解。
private AirLinePK id;
@Column(length=20)
private String name;
public AirLinePK getId() {
return id;
}
public void setId(AirLinePK id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


public class AirLineTest {
@Test
public void save(){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("sample");//形如sessionFactory
EntityManager em=factory.createEntityManager();
em.getTransaction().begin();
AirLinePK id=new AirLinePK();
id.setStartCity("SHA");
id.setEndCity("PEK");
AirLine airline=new AirLine();
airline.setId(id);
airline.setName("上海飞北京");
em.persist(airline);
em.getTransaction().commit();
em.close();
factory.close();
}
}

0 0
原创粉丝点击