Hibernate的映射文件中基于主键的双向1对1的关联

时间:2021-10-21 14:44:15

1、Hibernate中采用基于主键的映射策略是,有一端(任意一端)的主键生成策略要是foreign,根据对方的主键来生成自己的主键,它的实体不能拥有自己的主键生成策略,如我的配置文件:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="po">
<class name="Bike" table="tb_bike">
<!-- 使用只读缓存 catalog="danche" -->
<cache usage="read-write"/>
<!-- 映射标识属性 -->
<id name="bikeId" type="integer" column="b_bikeId">
<!-- 指定使用identity主键生成策略 -->
<generator class="native"/>
</id>
<!-- 映射普通属性 -->
<property name="bikeType" column="b_bikeType"
type="java.lang.String" length="45"/>
<property name="bikePrice" column="b_bikePrice"
type="java.lang.Double"/>
<property name="rentPrice" column="b_rentPrice"
type="java.lang.Double"/>
<property name="state" column="b_state"
type="java.lang.String"/>
<property name="picture" column="b_picture"
type="java.lang.String"/>
<property name="repair" column="b_repair"
type="java.lang.Integer"/>
<one-to-one name="order"></one-to-one>
</class>
</hibernate-mapping>

另一端是:

     <hibernate-mapping package="po">
<class name="Order" table="tb_order">
<!-- 使用只读缓存 catalog="danche" -->
<cache usage="read-write"/> <id name="orderId" type="integer" column="b_orderId">
<generator class="foreign">
<param name="property">bike</param>
</generator>
</id>
<!-- 映射普通属性 -->
<property name="userId" column="b_userId"
type="java.lang.Integer"/>
<property name="bikeId" column="b_bikeId"
type="java.lang.Integer"/>
<property name="orderTime" column="b_orderTime"
type="java.util.Date"/>
<!-- 主键双向关联-->
<one-to-one name="bike"></one-to-one>
</class>
</hibernate-mapping>

2、对应的,我们要在主键是foreign的持久化类中为其构造一个有参构造函数(用来在初始化是传递参数):

 public Order(){

     }
4 public Order(Integer userId,Integer bikeId,Date orderTime){
this.bikeId =bikeId;
this.userId = userId;
this.orderTime = orderTime;
}

3、之后的应用和普通的一个持久化类对应一个映射文件一样了。