Nhibernate - create a child by updating the parent or create explicitly?

What is the preferred method for creating child objects?

  • Adding a child to the collection on it is the parent and calling the parent update or
  • Explicitly creating a child, adding a child to the parent's collection, and updating the parent?

I am struggling with number 1. And it's complicated enough that I think No. 2 is preferable (less “magic”).

+1
source share
1 answer

Not sure what the “preferred method” will be (this may depend on who prefers it). But I can share my way.

If the parent is the root object, then we must save the entire link tree in one frame: session.SaveOrUpdate(parent) .

eg. Employee has a set of Educations . In this case, it should look like this

  • create Education give a link to the employee,
  • Add() to the employee.Educations collection.
  • Have / reverse the mapping, cascade = "all-delete-orphan" ...
  • NHibernate will do what we expect from session.SaveOrUpdate (parent)

Some snippets in xml:

 <class name="Employee" table="..." lazy="true" optimistic-lock="version" dynamic-update="true" batch-size="25" > <cache usage="read-write" region="ShortTerm"/> <id name="ID" column="Employee_ID" generator="native" /> <bag name="Educations" lazy="true" inverse="true" batch-size="25" cascade="all-delete-orphan" > <key column="Employee_ID" /> <one-to-many class="Education" /> </bag> ... 

And education

 <class name="Education" table="..." lazy="true" batch-size="25> <cache usage="read-write" region="ShortTerm"/> <id name="ID" column="Education_ID" generator="native" /> <many-to-one not-null="true" name="Employee" class="Employee" column="Employee_ID" /> ... 

on the run:

 public class EmployeeMap : ClassMap<Employee> { public EmployeeMap() { BatchSize(25) ... HasMany(x => x.Educations) .AsBag() .BatchSize(25) .LazyLoad() .Cascade.AllDeleteOrphan() .Inverse() .KeyColumn("Employee_ID") public class EducationMap : ClassMap<Education> { public EducationMap() { ... References(x => x.Employee, "Employee_ID") .Not.Nullable() ... 

And now the C # relationship:

 // business var employee = ...; var education = new Education { Employee = employee, ... }; employee.Educations.Add(education); // DAO session.SaveOrUpdate(employee); 

If the parent is not root, only the relation exists ( Employee has a set of Subordinates type Employee ), keep the persistent shared

+1
source

All Articles