1、Hibernate中采用基于主键的映射策略是,有一端(任意一端)的主键生成策略要是foreign,根据对方的主键来生成自己的主键,它的实体不能拥有自己的主键生成策略,如我的配置文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="po"> 6 <class name="Bike" table="tb_bike"> 7 <!-- 使用只读缓存 catalog="danche" --> 8 <cache usage="read-write"/> 9 <!-- 映射标识属性 --> 10 <id name="bikeId" type="integer" column="b_bikeId"> 11 <!-- 指定使用identity主键生成策略 --> 12 <generator class="native"/> 13 </id> 14 <!-- 映射普通属性 --> 15 <property name="bikeType" column="b_bikeType" 16 type="java.lang.String" length="45"/> 17 <property name="bikePrice" column="b_bikePrice" 18 type="java.lang.Double"/> 19 <property name="rentPrice" column="b_rentPrice" 20 type="java.lang.Double"/> 21 <property name="state" column="b_state" 22 type="java.lang.String"/> 23 <property name="picture" column="b_picture" 24 type="java.lang.String"/> 25 <property name="repair" column="b_repair" 26 type="java.lang.Integer"/> 27 <one-to-one name="order"></one-to-one> 28 </class> 29 </hibernate-mapping>
另一端是:
1 <hibernate-mapping package="po"> 2 <class name="Order" table="tb_order"> 3 <!-- 使用只读缓存 catalog="danche" --> 4 <cache usage="read-write"/> 5 6 <id name="orderId" type="integer" column="b_orderId"> 7 <generator class="foreign"> 8 <param name="property">bike</param> 9 </generator> 10 </id> 11 <!-- 映射普通属性 --> 12 <property name="userId" column="b_userId" 13 type="java.lang.Integer"/> 14 <property name="bikeId" column="b_bikeId" 15 type="java.lang.Integer"/> 16 <property name="orderTime" column="b_orderTime" 17 type="java.util.Date"/> 18 <!-- 主键双向关联--> 19 <one-to-one name="bike"></one-to-one> 20 </class> 21 </hibernate-mapping>
2、对应的,我们要在主键是foreign的持久化类中为其构造一个有参构造函数(用来在初始化是传递参数):
1 public Order(){ 2 3 } 4 public Order(Integer userId,Integer bikeId,Date orderTime){ 5 this.bikeId =bikeId; 6 this.userId = userId; 7 this.orderTime = orderTime; 8 }
3、之后的应用和普通的一个持久化类对应一个映射文件一样了。