Hibernate实现复合主键的使用

  1>:首先将要作为主键的属性首先抽取成单独的实体  并提供get And set方法  并且还需要序列化

      比如现在有一个实体 People ,具有属性pName,pAddress,pJavaScore,pCscore

     复合主键为pName,pAddress

   将这两个属性抽离形成一个新的实体并提供setter,gettter方法实现序列化

compositionkey.java

import java.io.Serializable;

/**
 * 
 * @author Guomin JIn
 *
 */
public class CompositionKey implements Serializable{
	private String pName;
	private String pAddress;
	public String getpName() {
		return pName;
	}
	public void setpName(String pName) {
		this.pName = pName;
	}
	public String getpAddress() {
		return pAddress;
	}
	public void setpAddress(String pAddress) {
		this.pAddress = pAddress;
	}
	
}

  2>:在实际的实体中申明主键实体的变量

抽离之后的Peopel实体如下:

People.java

package cn.pzhu.composition;
/**
 * 实体类
 * @author Guomin JIn
 *
 */
public class People {
	private CompositionKey key;
	private float pJavaScore;
	private float pCScore;
	public CompositionKey getKey() {
		return key;
	}
	public void setKey(CompositionKey key) {
		this.key = key;
	}
	public float getpJavaScore() {
		return pJavaScore;
	}
	public void setpJavaScore(float pJavaScore) {
		this.pJavaScore = pJavaScore;
	}
	public float getpCScore() {
		return pCScore;
	}
	public void setpCScore(float pCScore) {
		this.pCScore = pCScore;
	}
	@Override
	public String toString() {
		return "People [key=" + key + ", pJavaScore=" + pJavaScore + ", pCScore=" + pCScore + "]";
	}
	
	
}

  3>:在映射文件中编写实体的配置文件

配置文件如下:

hibernate.cfg.xml省略()

people.hbm.xml





    
   		
   			
   			
   		
        
		
    
4>:编写测试类

测试类使用junit

@Test
	public void test_0001() {
		Session session=new Configuration()
		.configure("hibernate.cfg.xml")
		.addClass(People.class)
		.buildSessionFactory()
		.openSession();
		
		session.beginTransaction();
		
		CompositionKey key=new CompositionKey();
		key.setpName("jgm");
		key.setpAddress("chengdu");
		
		People people=new People();
		people.setKey(key);
		people.setpJavaScore(12.34f);
		people.setpCScore(36.2f);
		//HibernateUtil.save(people);
		session.save(people);
	}



你可能感兴趣的:(Hibernate实现复合主键的使用)