Hibernate one-to-one 共享主键

    在项目中由于业务原因要对数据库中一个表做扩展,由于扩展的内容比较多,于是新建了一张表,表旧表做一对一关联,共享其旧表的主键。

    贴出个小例子供自己备忘使用

   我们这里用的是表名称:basic表和extend表

   Basic.java 和Basic.hbm.xm如下 

   package com.sszd.hibernate;

publicclassBasic{

privateintid;

privateStringfeilda;

privateExtendextend;

publicExtendgetExtend(){

returnextend;

}

publicvoidsetExtend(Extendextend){

this.extend=extend;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetFeilda(){

returnfeilda;

}

publicvoidsetFeilda(Stringfeilda){

this.feilda=feilda;

}

}

<?xml version="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<classname="com.sszd.hibernate.Basic"table="basic">

<idname="id"column="id">

<generatorclass="native"/>

</id>

<propertyname="feilda"column="feilda"type="string"/>

<!--cascade表示级联关系,extend伴随着basic的操作面操作-->

<one-to-onename="extend"class="com.sszd.hibernate.Extend"cascade="all"></one-to-one>

</class>

</hibernate-mapping>

Extend.java和Extend.hbm.xml

package com.sszd.hibernate;

publicclassExtend{

privateintid;

privateStringfeilda;

privateBasicbasic;

publicBasicgetBasic(){

returnbasic;

}

publicvoidsetBasic(Basicbasic){

this.basic=basic;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetFeilda(){

returnfeilda;

}

publicvoidsetFeilda(Stringfeilda){

this.feilda=feilda;

}

}

<?xml version="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

"-//Hibernate/HibernateMappingDTD3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mappingpackage="com.sszd.hibernate">

<classname="com.sszd.hibernate.Extend"table="extend">

<idname="id"column="id">

<generatorclass="foreign">

<paramname="property">basic</param>

</generator>

</id>

<propertyname="feilda"column="feilda"/>

<one-to-onename="basic"class="com.sszd.hibernate.Basic"constrained="true"></one-to-one>

</class>

</hibernate-mapping>

相关推荐