JPA联合主键

JPA联合主键是使用一个类作为实体的主键

/**
 * 使用复合主键要满足的条件
 * 1、要实现序列化 
 * 2、提供默认的构造方法
 * 3、实现hashCope
 * 4.使用@Embeddable注解类
 * 5.引用联合主键的id加@EmbeddedId注解
 */

 

src下在面的META-INF/persistence.xml配置如下:

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
  <persistence-unit name="itcast" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="root"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&amp;characterEncoding=UTF-8"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
  </persi

 联合主键类

@SuppressWarnings("serial")
@Embeddable  //embeddable: 可嵌入的
public class AirLinePk implements java.io.Serializable {
    @Column(length = 3)
    private String startCity;// 出发城市

    @Column(length = 3)
    private String endCity;// 抵达城市

    public AirLinePk() {
        super();
    }

    public AirLinePk(String startCity, String endCity) {
        super();
        this.startCity = startCity;
        this.endCity = endCity;
    }

    public String getEndCity() {
        return endCity;
    }

    public void setEndCity(String endCity) {
        this.endCity = endCity;
    }

    public String getStartCity() {
        return startCity;
    }

    public void setStartCity(String startCity) {
        this.startCity = startCity;
    }

    @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;
    }

}

 实体:

@SuppressWarnings("serial")
@Entity
public class AirLine implements java.io.Serializable {
	@EmbeddedId
	private AirLinePk id;
	@Column(length = 20)
	private String name;

	public AirLine() {
		super();
	}

	public AirLine(String startCity, String endCity, String name) {
		this.id = new AirLinePk(startCity, endCity);
		this.name = 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("itcast");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();

		em.persist(new AirLine("PEK", "SHA", "北京飞上海"));
		//em.persist(new AirLine("HK1", "SZ!", "香港飞深圳"));
		em.getTransaction().commit();
		em.close();
		factory.close();

	}
	/**
	 * 查找
	 */
	@Test
	public void find() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		AirLine airLine = em.find(AirLine.class, new AirLinePk("PEK", "SHA"));
		System.out.println(airLine.getName());
		em.getTransaction().commit();
		em.close();
		factory.close();

	}
	/**
	 * 更新
	 */
	@Test
	public void update() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		AirLine airLine = em.getReference(AirLine.class, new AirLinePk("PEK", "SHA"));
		airLine.setName("北京飞上海北京飞上海");
		em.merge(airLine);
		em.getTransaction().commit();
		em.close();
		factory.close();

	}
	/**
	 * 列表
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@Test
	public void list() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		List<AirLine> airLines = em.createQuery("select o from AirLine o").getResultList();
		for (AirLine air : airLines) {
			System.out.println(air.getName());
		}
		em.getTransaction().commit();
		em.close();
		factory.close();

	}
	/**
	 * 删除
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@Test
	public void detele() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		em.remove(em.getReference(AirLine.class, new AirLinePk("PEK", "SHA")));
		em.getTransaction().commit();
		em.close();
		factory.close();

	}

	/**
	 * 用来判断映射是否成功
	 * 
	 */
	@Test
	public void test() {
		Persistence.createEntityManagerFactory("itcast");
	}

}

 联合主键映射关系:


JPA联合主键_第1张图片
 

你可能感兴趣的:(jpa,联合主键,@EmbeddedId,Embeddable)