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>



[b]测试[/b]

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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值