hibernate中的双向映射

时间:2014-03-11 19:23:55

标签: java hibernate bidirectional hibernate-onetomany

我有两个表,引号和quotation_item。他们之间有一对多的关系。我的要求是当我执行quotation.setQuotationItem(set)时,应该删除映射到引用的旧quotationItem,并且set中的quotationItems应该映射到引号。

/ * ** 我的报价pojo就像 * ** * /

    public class Quotation {
    int quotationId;
    String code;
    String clientName;
    Set<QuotationItem> quotationItem=new HashSet<QuotationItem>();
    //getter and setter
    }

/ * ** QuotationItem POJO * *** /

    public class QuotationItem extends Quotation{
    int id;
    Quotation quotation;
    String itemName;
    int rate;
    int qty;
    //getter and setter
    }

/ * * Quotation.hbm * ** * **** /

    <hibernate-mapping>
    <class name="com.paramatrix.pojo.Quotation" table="quotation" >
    <id name="quotationId" type="int" column="quotation_id">
    <generator class="native" />
    </id>
    <property name="code" column="code" type="string" />
    <property name="clientName" column="client_name" type="string" />
    <set name="quotationItem" table="quotation_item" cascade="save-update" inverse="true">
    <key>
    <column name="quotation_id" not-null="true" />
    </key>
    <one-to-many class="com.paramatrix.pojo.QuotationItem" />
    </set>
    </class>
    </hibernate-mapping>

/ ** QuotationItem.hbm * ** * ** /

    <class name="com.paramatrix.pojo.QuotationItem" table="quotation_item" dynamic-insert="true">
    <id name="id" type="int" column="id">
    <generator class="native" />
    </id>
    <many-to-one name="quotation" class="com.paramatrix.pojo.Quotation" >
    <column name="quotation_id" not-null="true" />
    </many-to-one>
    <property name="itemName" column="item_name" type="string" />
    <property name="rate" column="rate" type="int" />
    <property name="qty" column="qty" type="int" />
    </class>

我的表格结构是这样的 报价

quotation_id code client_name

我的Quotation_item表结构

id quotation_id item_name rate qty

1 个答案:

答案 0 :(得分:0)

尝试修改集而不是替换它。即:

    quotation.getQuotationItem().clear();
    quotation.getQuotationItem().addAll(newSet);

这是由于一些冬眠奇怪。

除此之外,还有一点关于命名。您的Quotation.quotationItem应该被命名为quotationItems,因为它包含多个QuotationItem