0

I have a model like this:

class Foo
{
    public IList<HistoryRecord> History {get;set;}
    public HistoryRecord HistoryReference {get;} //Computed, null or item from History.
}

Which I tired to map like this:

<list name="History" cascade="all-delete-orphan" inverse="false" table="history">
      <key column="foo_fk" not-null="true" update="false"/>
      <index column="idx"/>
      <one-to-many class="HistoryRecord" />
</list>
<many-to-one name="HistoryReference" cascade="none" access="readonly" column="history_ref" class="HistoryRecord"/>

It works but produce, redundant SQL:

  1. INSERT INTO foo... --not specifying history_ref, it inserts NULL.
  2. N INSERTS INTO history.. all good.
  3. UPDATE foo set history_ref=, prop1=, prop2=, etc NH redundantly updates history_ref, which could be inserted at 1. and all properties of Foo.

I want to get rid of 3. redundant update and set history_ref during insert.

Alex Burtsev
  • 12,418
  • 8
  • 60
  • 87

1 Answers1

0

I was able to make this work, by changing cascade order on many-to-one side from NONE to ALL.

<many-to-one name="HistoryReference" cascade="ALL" access="readonly" column="history_ref" class="HistoryRecord"/>

But beware that in this configuration childs are inserted BEFORE parent, so if you have FK constraint on you child to parent link (and you really should) it will throw exception, because your child references parent which doesn't exist yet. To overcome it you have to use DEFERRABLE constraint in your DB, which is checked on transaction commit, and not at insert moment.

Alex Burtsev
  • 12,418
  • 8
  • 60
  • 87