黑马程序员_JAP中关于复合主键的细节

代码如下:

package cn.mu.bean;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class AirLinePK implements Serializable{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	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;
	}

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

	public void setStartCity(String startCity) {
		this.startCity = startCity;
	}
	@Column(length=3)
	public String getEndCity() {
		return endCity;
	}

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

}

 

package cn.mu.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(String startCity,String endCity,String name) {
		this.id = new AirLinePK(startCity, endCity);
		this.name=name;
	}
	
	public Airline(AirLinePK id) {
		this.id = id;
	}
	@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 junit.text;

import static org.junit.Assert.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.BeforeClass;
import org.junit.Test;

import cn.mu.bean.Airline;

public class AirLineTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void savetest() {
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory("mu");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();// 开始事务
		em.persist(new Airline("PEK","SHA","上海"));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
}

 

posted on 2012-09-11 15:33  小木の故事  阅读(286)  评论(0)    收藏  举报

导航