質問

I'm trying to map the following classes:

PessoaFisica and PessoaJuridica inherits Pessoa. Cliente has an association with Pessoa, it may be PessoaJuridica or PessoaFisica.

When I save a Cliente object with PessoaFisica, for example, thats ok. But when I try to update and I set the property Pessoa from Cliente to PessoaJuridica and try to update, it updates, but it generates a new row in table TB_PESSOA and the old row, in PessoaFisica is not deleted. It creates a new row to PessoaJuridica, but the old row remains. What's wrong with my mapping XMLs ? Why NHibernate does not delete the old row before insert the new polymorphic object ?

Those are the mapping files I am using

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="SALClassLib.Masterdata.Model" assembly="SALClassLib">
<class name="Pessoa" table="TB_PESSOA">
<id name="Id">
  <column name="ID_PESSOA" not-null="true"/>
  <generator class="increment" />
</id>

(other properties...)

<joined-subclass name="PessoaFisica" table="TB_PESSOA_FISICA">
    <key column="ID_PESSOA" />
    (other properties...)
</joined-subclass>

 <joined-subclass name="PessoaJuridica" table="TB_PESSOA_JURIDICA">
    <key column="ID_PESSOA" />
    (other properties...)
 </joined-subclass>
 </class>

<class name="Cliente" table="TB_CLIENTE">
<id name="Id">
  <column name="ID_CLIENTE" not-null="true"/>
  <generator class="increment" />
</id>
<many-to-one name="Pessoa" class="Pessoa" cascade="all" column="ID_PESSOA" not-null="true" unique="true" />

Thank you

役に立ちましたか?

解決

NHibernate cascading is nicely explained here: NHibernate Cascades: the different between all, all-delete-orphans and save-update

One of the option, is cascade="all-delete-orphan" which could be seen as what you are asking for.

BUT

Cascading deletion of the orphans is correct only in parent-child scenario (no parent ==> no children) or one-to-one mapping. (i.e not vice versa child-parent)

In your case, you do ask for deletion of the referenced object. But NHibernate (well no-one) can know, if it is not referenced by some other "child".

If you need to delete previous Person assigned, you can always do it in code - but explicitly

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top