JPA連携キー
3132 ワード
/**
*
*
* 1、 Serializable 2、 3、 hashCode equals
*
* @Embeddable ( )
* @author
*
*/
@Embeddable
public class AirLinePK implements Serializable {
private String staCity;
private String endCity;
public AirLinePK() {
}
public AirLinePK(String staCity, String endCity) {
this.staCity = staCity;
this.endCity = endCity;
}
@Column(nullable = false, length = 32)
public String getStaCity() {
return staCity;
}
public void setStaCity(String staCity) {
this.staCity = staCity;
}
@Column(nullable = false, length = 32)
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 + ((staCity == null) ? 0 : staCity.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;
final AirLinePK other = (AirLinePK) obj;
if (endCity == null) {
if (other.endCity != null)
return false;
} else if (!endCity.equals(other.endCity))
return false;
if (staCity == null) {
if (other.staCity != null)
return false;
} else if (!staCity.equals(other.staCity))
return false;
return true;
}
}
このフルプライマリ・キーの適用:
@Entity
@Table(name = "AIRLINE")
public class AirLineEntity {
private AirLinePK a_id;
private String a_name;
//
@EmbeddedId
public AirLinePK getA_id() {
return a_id;
}
public void setA_id(AirLinePK a_id) {
this.a_id = a_id;
}
@Column(length = 50)
public String getA_name() {
return a_name;
}
public void setA_name(String a_name) {
this.a_name = a_name;
}
}
テスト:
public class CompositePKTest {
@Test
public void save(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("mengya");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
AirLineEntity airLine = new AirLineEntity();
airLine.setA_id(new AirLinePK("BeJing","ShangHai"));
airLine.setA_name(" ");
em.persist(airLine);
em.getTransaction().commit();
em.close();
factory.close();
}
}