欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JPA(六)之联合主键

程序员文章站 2022-03-02 15:33:01
...

1.顾名思义:复合主键就是指多个主键联合形成一个主键组合

2.背景介绍:比如原则上航线是由出发地及目的地确定,所以,如果要设置航线的id可以用出发地和目的地来表示。

3.persistence.xml内容不变

4.实体bean

  主键类:

 

package com.sinoi.bean;

import java.io.Serializable;

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

@Embeddable
public class AirlinePK implements Serializable{
	@Column(length=3, nullable=false)
	private String startCity;
	@Column(length=3, nullable=false)
	private String endCity;

	public AirlinePK(String startCity, String endCity) {
		this.startCity = startCity;
		this.endCity = endCity;
	}
	
	public String getStartCity() {
		return startCity;
	}
	public void setStartCity(String startCity) {
		this.startCity = startCity;
	}
	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.sinoi.bean;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;

@Entity
public class Airline {
	@EmbeddedId
	private AirlinePK id;
	@Column(length=10, nullable=false)
	private String name;
	
	public Airline() {}
	
	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;
	}
	
}

 

5.测试

 

package junit.test;

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

import org.junit.Test;

import com.sinoi.bean.Airline;


public class UnitTest {
	@Test
	public void save() {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("unitname");
		EntityManager manager = factory.createEntityManager();
		manager.getTransaction().begin();
		
		manager.persist(new Airline("PEK", "SHA", "PeToShang"));
		
		manager.getTransaction().commit();
		manager.close();
		factory.close();
	}
}

 

 

转载于:https://my.oschina.net/beanGo/blog/168993