联合主键的一些知识:
使用@EmbeddedId标示联合主键;
在联合主键类中只是定义确定联合主键的字段即可;
* 联合主键类的规则
* 1.必须包含一个无参的构造函数
* 2.必须实现序列化接口
* 3.必须重写hashCode和equals方法,而且equals方法的参数必须包括确定联合主键的所有字段
联合主键类的定义:
package com.yl.demo1.bean.JointPK; import java.io.Serializable; import javax.persistence.Column;
import javax.persistence.Embeddable; /**
* 在联合主键类中只是定义确定联合主键的字段即可
* 联合主键类的规则
* 1.必须包含一个无参的构造函数
* 2.必须实现序列化接口
* 3.必须重写hashCode和equals方法,而且equals方法的参数必须包括确定联合主键的所有字段
* @author yul
*
*@Embeddable--告诉其它类,在使用AieLinePK时只是使用AieLinePK的属性作为实体的持久化属性
*/ @Embeddable //嵌入
public class AirLinePK implements Serializable {
private String startCity;//航空中每个城市都有一个三位的字母标识符
private String endCity; public AirLinePK(){} public AirLinePK(String startCity, String endCity) {
this.startCity = startCity;
this.endCity = endCity;
}
@Column(length=3)
public String getStartCity() {
return startCity;
}
public void setStartCity(String startCity) {
this.startCity = startCity;
}
@Column(length=3)
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;
} }
package com.yl.demo1.bean.JointPK; import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity; @Entity
public class AirLine {
private AirLinePK id;
private String name; public AirLine(){} public AirLine(AirLinePK id) {
this.id = id;
} public AirLine(String startCity, String endCity, String name) {
this.id = new AirLinePK(startCity, endCity);
this.name = name;
} @EmbeddedId
public AirLinePK getId() {
return id;
}
public void setId(AirLinePK id) {
this.id = id;
}
@Column(length=20)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
常用操作:
@Test
public void save() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("YL");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();//事务开始 em.persist(new AirLine("PEK", "SHA", "北京飞上海")); em.getTransaction().commit();
em.close();
factory.close();
}