hibernate 全面学习【hibernate 复合主键映射】

复合主键映射

通常将复合主键相关属性,单独抽取出来,建立一个独立的类
  * 必须实现序列化接口
  * 必须实现equals和hashcode方法
 
  采用<composite-id>标签进行映射,其它属性采用<property>正常映射
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.bjsxt.hibernate.FiscalYearPeriod" table="t_fiscal_year_period">
		<composite-id name="fiscalYearPeriodPK">
			<key-property name="fiscalYear" column="fiscal_year"/>
			<key-property name="fiscalPeriod" column="fiscal_period"/>
		</composite-id>
		<property name="beginDate" column="begin_date"/>
		<property name="endDate" column="end_date"/>
		<property name="periodSts" column="period_sts"/>
	</class>
</hibernate-mapping>	



测试
package com.bjsxt.hibernate;

import java.util.Date;

import org.hibernate.Session;

import junit.framework.TestCase;

public class FiscalYearPeriodTest extends TestCase {
	
	public void testSave() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			//复合主键
			FiscalYearPeriodPK fiscalYearPeriodPK = new FiscalYearPeriodPK();
			fiscalYearPeriodPK.setFiscalYear(2007);
			fiscalYearPeriodPK.setFiscalPeriod(8);
			
			FiscalYearPeriod fiscalYearPeriod = new FiscalYearPeriod();
			
			//和主键建立关联
			fiscalYearPeriod.setFiscalYearPeriodPK(fiscalYearPeriodPK);
			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();
			//复合主键
			FiscalYearPeriodPK fiscalYearPeriodPK = new FiscalYearPeriodPK();
			fiscalYearPeriodPK.setFiscalYear(2007);
			fiscalYearPeriodPK.setFiscalPeriod(8);
			FiscalYearPeriod fiscalYearPeriod = (FiscalYearPeriod)session.load(FiscalYearPeriod.class, fiscalYearPeriodPK);
			System.out.println("beginDate=" + fiscalYearPeriod.getBeginDate());
			System.out.println("endDate=" + fiscalYearPeriod.getEndDate());
			System.out.println("periodSts=" + fiscalYearPeriod.getPeriodSts());
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}

}

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