现在的位置: 首页 > 综合 > 正文

hibernate一对多问题处理

2018年01月28日 ⁄ 综合 ⁄ 共 1963字 ⁄ 字号 评论关闭

hibernate 用了不少时间,一直没有做过什么总结,每次碰到问题就倒腾几下好了就过去了。这次下决心立文,以后碰到问题就加在后面。

举两个不同的例子:

例1:问题 - -> 多选答案【一对多,采用list方式】

QuestionModel 配置文件:

<list name="selectionList" cascade="all" inverse="true" lazy="false"><!-- selectionList为private List<SelectionModel>  selectionList;-->
            <key>
                <column name="QUESTION_ID" not-null="true"/><!-- Selection表里的外键 -->
            </key>
            <index column="SEL_NO" /><!-- list是有序的,需要新增加一个额外的排序字段供hibernate使用 -->
            <one-to-many class="com.xxx.model.SelectionModel" />
        </list>

SelectionModel配置文件:

<many-to-one name="question" class="com.xxx.model.QuestionModel" fetch="select">
            <column name="QUESTION_ID" precision="22" scale="0" /><!-- Selection表里的外键 -->
        </many-to-one>

selectionTable:

例2:问题类型 - -> 问题【一对多,采用set】

QuestionTypeModel的配置文件:

<set name="questionModel" inverse="true" cascade="all">
            <key>
                <column name="TYPE_ID" precision="22" scale="0" /><!-- Question表里的外键 -->
            </key>
            <one-to-many class="com.xxxx.model.QuestionModel" />
        </set>

QuestionModel的配置文件:

        <many-to-one name="questionTypeModel" 
        class="com.xxxx.model.QuestionTypeModel" 
        fetch="select" lazy="false">
            <column name="TYPE_ID" precision="22" scale="0" />
        </many-to-one>

例3: 购物车- -> 商品清单【一对多, 采用bag】

ShoppingCart 的配置文件:

<bag name="items" order-by="id asc" lazy="false" inverse="true">  
  <key column="cartId" /><!-- productitem的外键 --> 
  <one-to-many class="com.xxxx.model.ProductItem"/>  
</bag>

ProductItem 的配置文件:

<many-to-one name="cart" 
        class="com.xxxx.model.ShoppingCart" 
        fetch="select" lazy="false" cascade="all" outer-join="true">
            <column name="cartId" precision="20" scale="0" /><!-- productitem的外键 --> 
        </many-to-one>

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

常见问题:

no1: 保存时出现:org.hibernate.TransientObjectException:
 object references an unsaved transient instance - save the transient instance before flushing: com.xxxx.model.ProductItem

问题解决方法是之前忘记在“一”方(购物车)中加入 inverse="true" ,加上就好了。

(未完待续..)

抱歉!评论已关闭.