package cn.itcast.bean;
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) {
super();
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;
}
}
------------------------------------------------------------------
package cn.itcast.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
*
* @Embeddable只使用這個實體內的屬性
*
*/
@Embeddable
public class AirLinePK implements Serializable {
private String startCity;
private String endCity;
public AirLinePK(){}
public AirLinePK(String startCity, String endCity) {
super();
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;
final 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;
}
}
-----------------------------------------------------------------
junit測試
package junit.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.BeforeClass;
import org.junit.Test;
import cn.itcast.bean.AirLine;
public class AirLineTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test public void save()
{
EntityManagerFactory factory=Persistence.createEntityManagerFactory("itcast");
EntityManager em=factory.createEntityManager();
em.getTransaction().begin();
em.persist(new AirLine("PEK","SHA","北京飛上海"));
em.getTransaction().commit();
em.close();
factory.close();
}
}