views:

2616

answers:

2

I have a one-to-one relationship between a Company class and a CompanySettings class. When I create a new Company object, (a CompanySettings object is created in Company's constructor for its Settings property), and then

SaveOrUpdate(session, companyObject)

I expect the INSERT to cascade from the Company to the CompanySettings. However, this does not happen unless I explicitly call SaveOrUpdate on the CompanySettings object as well.

Mapping files shown below:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"`>
  <class name="AST.Domain.Company, AST.Domain" table="Companies">
    <id name="EntityID" column="CompanyId">
      <generator class="guid.comb" />
    </id>
    <property name="CompanyName" />
    . . .
    <one-to-one name="Settings" class="AST.Domain.CompanySettings, AST.Domain"
                constrained="true" lazy="false" />
  </class>
</hibernate-mapping>

My mapping file for the Company Settings class:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="AST.Domain.CompanySettings, AST.Domain" table="CompanySettings">
    <id name="EntityID" column="CompanyId">
      <generator class="foreign">
        <param name="property">Company</param>
      </generator>
    </id>
    <property name="MaxUsers" />
    <one-to-one name="Company" class="AST.Domain.Company, AST.Domain" />
  </class>
</hibernate-mapping>
+4  A: 

Have you tried specifying cascade="all" on your one-to-one mapping?

Darin Dimitrov
+1  A: 

Set the cascade attribute of the one-to-one in the Company mapping.

But, on another note: Have you thought of mapping the CompanySettings as a 'component' of Company instead of a separate entity ?

Isn't it so that 'CompanySettings' is a 'value object', and should be mapped better as a component ?

By doing this, you can put the CompanySettings values in the same table as 'Company', but it will be treated as a separate class.

Since this is a one-to-one mapping, I think it is a better option for your data model as well.

Then, your mapping would look something like this:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"`>
  <class name="AST.Domain.Company, AST.Domain" table="Companies">
    <id name="EntityID" column="CompanyId">
      <generator class="guid.comb" />
    </id>
    <property name="CompanyName" />
    . . .
    <component name="Settings" class="AST.Domain.CompanySettings, AST.Domain">
        <property name="MaxUsers" />
    </component>
  </class>
</hibernate-mapping>

You will have indeed 2 separate objects (Company & CompanySettings, and Company will have a 'Companysettings' object, but the settings will be saved in the Company table).

Or, is there any special reason on why you've put the CompanySettings in a separate table ? I mean, it is a one-to-one relation so this is completely not necessary (and imho even a bad practice :) ).

Frederik Gheysels

related questions