联合主键就是将几个字段都作为主键,或者说一个以上主键的都可作为联合主键或者复合主键,开发联合主键实体类对象必须做到三个要求,一是提供一个无参构造函数,二是必须实现序列化串行接口,三是必须重写HashCode和equals方法,参数是复合主键的属性。这里我们的实例用航班做,我们知道航班有起始地,也有终止点,他们有一个共同的航班名,所以可以用联合主键来做表设计,具体看代码。
/**
* 航线实体
*/
@Entity
@Table(name="t_airline")
public class AirLine {
@EmbeddedId
private AirLinePK id;
@Column(length=20,nullable=false)
private String name;
public AirLine(){}
//默认构造函数中引入联合主键参数
public AirLine(String startCity,String endCity,String name) {
this.id=new AirLinePK(startCity, endCity);
this.name = name;
}
}<span style="font-family:Microsoft YaHei;font-size:14px;">
</span>
/**
* 复合主键类
* 1.提供一个无参构造函数
* 2.必须实现序列化接口
* 3.必须重写HashCode和equals方法,参数是复合主键的属性
*
* Embeddable表示它标识的类是用在别的实体里面
*/
@Embeddable
public class AirLinePK implements Serializable{
@Column(length=3,nullable=false)
private String startCity;
@Column(length=3,nullable=false)
private String endCity;
public AirLinePK() {
}
public AirLinePK(String startCity, String endCity) {
this.startCity = startCity;
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;
}
<!--省略。。注意联合主键要求 -->
}<span style="font-family:Microsoft YaHei;font-size:14px;">
</span>
public class CompositePK {
private static EntityManagerFactory factory;
private static EntityManager em;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
factory = Persistence.createEntityManagerFactory("jpatest1");
em = factory.createEntityManager();
}
@Test
public void save() {
em.getTransaction().begin(); //开启事务
AirLine line = new AirLine("PEK", "SHA", "北京飞往上海");
em.persist(line);
em.getTransaction().commit(); //提交事务
em.close(); //关闭
factory.close(); //关闭
}
}
好了,联合主键就搞定了,,还是得多敲代码。原文地址:http://blog.csdn.net/zeb_perfect/article/details/42367855