(**)hibernate中基于主键和基于外键的one-to-one

来源:互联网 发布:汽配数据服务商 编辑:程序博客网 时间:2024/05/22 17:25
基于主键的单向 1-1 
     基于主键关联的持久化类不能拥有自己的主键生成器,它的主键由关联类负责生成。
     one-to-one:必须为one-to-one元素增加constrained="true"属性,表明该类的主键由关联类生成
    【要点】Person - IdCard
     <id name=”id”>
<generator class=”foreign”><param name=”property”>idCard</param></generator>
     <id>
     <one-to-one name=”idCard” constrained=”true”/>
基于外键的单向1-1
     和<many-to-one>N-1相同,多添加一个unique="true" 属性,用以表示N的一端必须唯一,加了唯一约束,即成了1-1
     【举例】
     <one-to-one name=”idCard” property-ref=“person”/>
             
     <many-to-one name=”person” column=”person_id” unique=”true” not-null=”true”/>

     property-ref:用于指定关联类的一个属性,这个属性将会和本外键相对应 

举例

1、基于主键的单向1-1

Person:PK id  其他name、age

id_card:PK,FK  id  其他useful_life

IdCard.hbm.xml

<hibernate-mapping>    <class name="cn.itcast.hibernate.domain.IdCard" table="id_card" catalog="test">        <id name="id" type="java.lang.Integer">          <generator class="foreign">             <param name="property">person</param>          </generator>        </id>        <one-to-one name="person" class="cn.itcast.hibernate.domain.Person" constrained="true"></one-to-one>        <property name="usefulLife" type="java.util.Date">            <column name="useful_life" length="10" not-null="true" />        </property>    </class></hibernate-mapping>

2、基于外键的1-1

Person:PK id  其他name、age

id_card:PK id    FK  useful_life  person_id

IdCard.hbm.xml

<hibernate-mapping>    <class name="cn.itcast.hibernate.domain.IdCard" table="id_card" catalog="test">        <id name="id" type="java.lang.Integer">            <column name="id" />            <generator class="native"></generator>        </id>        <many-to-one name="person" class="cn.itcast.hibernate.domain.Person" update="false" insert="false" fetch="select">            <column name="id" not-null="true" unique="true" />        </many-to-one>        <property name="usefulLife" type="java.util.Date">            <column name="useful_life" length="10" not-null="true" />        </property>    </class></hibernate-mapping>

在此处跌倒多次,必须注意了啊!!



原创粉丝点击