hibernate Composite复合(联合)主键映射

复合(联合)主键映射

通常将复合主键相关的属性,单独放到一个类中
 * 此类必须实现序列化接口
 * 覆写hashcode和equals方法

 

1、实体

public class FiscalYearPeriod {
	
	private FiscalYearPeriodPK fiscalYearPeriodPK;
	
	//开始日期
	private Date beginDate;
	
	//结束日期
	private Date endDate;
	
	//状态
	private String periodSts;
。。。

 

public class FiscalYearPeriodPK implements Serializable {

	//核算年
	private int fiscalYear;
	
	//核算月
	private int fiscalPeriod; ...

 

 2、映射文件

<hibernate-mapping>
	<class name="com.bjsxt.hibernate.FiscalYearPeriod" table="t_fiscal_year_period">
		<composite-id name="fiscalYearPeriodPK">
			<key-property name="fiscalYear"/>
			<key-property name="fiscalPeriod"/>	
		</composite-id>
		<property name="beginDate"/>
		<property name="endDate"/>
		<property name="periodSts"/>
	</class>
</hibernate-mapping>

 

3、TestCase

package com.bjsxt.hibernate;

import java.util.Date;

import org.hibernate.Session;

import junit.framework.TestCase;

public class CompositeMappingTest extends TestCase {

	public void testSave1() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			FiscalYearPeriod fiscalYearPeriod = new FiscalYearPeriod();

			FiscalYearPeriodPK pk = new FiscalYearPeriodPK();
			pk.setFiscalYear(2009);
			pk.setFiscalPeriod(8);
			
			fiscalYearPeriod.setFiscalYearPeriodPK(pk);
			
			fiscalYearPeriod.setBeginDate(new Date());
			fiscalYearPeriod.setEndDate(new Date());
			fiscalYearPeriod.setPeriodSts("Y");
			
			session.save(fiscalYearPeriod);
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}		
	
	public void testLoad1() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			FiscalYearPeriodPK pk = new FiscalYearPeriodPK();
			pk.setFiscalYear(2008);
			pk.setFiscalPeriod(8);
			
			FiscalYearPeriod fiscalYearPeriod = (FiscalYearPeriod)session.load(FiscalYearPeriod.class, pk);
			
			System.out.println(fiscalYearPeriod.getPeriodSts());
			
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}			
}

 

你可能感兴趣的:(Hibernate,JUnit)