2011-08-16 39 views
0

我有2個類,ForecastCost,它們之間定義了多對多關係。我們現在在鏈接表中添加了「訂單」列(因此,我們的客戶可以在Forecast內指定Cost的訂單)。爲了在我們的映射中反映出這一點,我們創建了一個新實體ForecastCost並將ForecastCost之間的多對多替換爲Forecast 1- * ForecastCost * -1 Cost返回「對象引用未保存的瞬態實例」

的映射是這樣的:

Forecast.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="FinRep" assembly="FinRep"> 
    <class name="Forecast" table="FORECAST" polymorphism="implicit"> 
    <id name="Id" column="PKFORECAST" type="long" access="field.camelcase" unsaved-value="0"><!-- ... --></id> 

    <!-- ... --> 

    <bag name="KostComponenten" table="FORECASTCOST" access="field.camelcase" lazy="false" cascade="save-update"> 
     <key column="FKFRBFORECAST"></key> 
     <one-to-many class="ForecastCost" /> 
    </bag> 
    </class> 
</hibernate-mapping> 

ForecastCost.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="FinRep" assembly="FinRep"> 
    <class name="ForecastCost" table="FORECASTCOST"> 
     <composite-id name="ForecastCostId" class="FinRep.ForecastCostKey, FinRep"> 
      <key-many-to-one name="Forecast" column="FKFORECAST" lazy="false" class="FinRep.Forecast, FinRep" /> 
      <key-many-to-one name="Cost" column="FKCOST" lazy="false" class="FinRep.Cost, FinRep" /> 
     </composite-id> 

     <property name="Order" column="ORDER" /> 
    </class> 
</hibernate-mapping> 

首先, '級聯' Forecast映射中的包上沒有設置屬性,所以當我試圖保存Forecast有一些Cost鏈接到它,我會(理所當然地)得到一個錯誤,說有關的ForecastCost對象不能從數據庫中檢索。我認爲加入'cascade'屬性會解決這個問題,但是現在當我嘗試保存Forecast#1(例如)時,我得到一個異常,說明類型爲= Forecast entity = 1的object references an unsaved transient instance - save the transient instance before flushing

我認爲正在發生的事情是,它試圖挽救預測如何,並通過這樣做,也試圖堅持鏈接到它所有的ForecastCost/Cost對象,但ForecastCost對象也有一個鏈接回Forecast實體我們正在保存(但還沒有保存,因此是暫時的),所以它出錯了。

我應該怎麼做才能解決這個問題?

+0

東西我剛剛發現 - 使用時,我只能得到錯誤'SaveOrUpdateCopy'。當使用'SaveOrUpdate'時,一切正常。 – efdee

回答

0

只是另一個讓你留在你的課程的aproach。

class ForeCast 
{ 
    // public virtual ICollection<Kost> KostComponenten { get; set; } // old 
    public virtual IList<Kost> KostComponenten { get; set; }   // new 
} 

並將其映射:

<list name="KostComponenten" table="FORECASTCOST" access="field.camelcase" lazy="false" cascade="save-update"> 
    <key column="FKFRBFORECAST"/> 
    <index column="order"/> 
    <many-to-many class="ForecastCost" /> 
</bag> 

那麼要想在列表中,你可以做KostComponenten.Insert(...)KostComponenten.Add(...)

+0

這是我原來的計劃,但我讀過NHibernate在訂單序列(例如1,2,4,5)存在差距或存在重複時(0,0,0)時不會很好地反應 - 必然會發生,我可以輕鬆解決,只需在客戶端訂購... – efdee

+0

@efdee您如何維護訂單?如果您使用IList的_add_,_insert_和_remove_,那麼不應該有0,0,0,並將空位視爲空列表中的空指針 – Firo

+0

首先,我們在數據庫中已有很多條目,默認情況下,它們的順序現在將設置爲0,這僅僅是一個問題。其次,我不希望刪除導致所有其他行的更新(以修復其索引)。這對我現在的用例來說並不現實。 – efdee

相關問題