NHibernate: Avoiding complete in-memory collections when working with child collections via aggregate root - nhibernate

Considering the simplified class below, lets assume:
that the parent can have a relatively large amount of children (e.g. 1000)
the child collection is lazy loaded
we have loaded one parent via it's Id from a standard Get method of a ParentRepository, and are now going to read the OldestChild property
class Parent
{
public IList<Child> Children { get; set; }
public Child OldestChild
{
get { return Children.OrderByDescending(c => c.Age).FirstOrDefault();
}
}
When using NHibernate and Repositories, is there some best practice approach to satisfy both:
a) Should select oldest child through the aggregate root (Parent) - [ie. without querying the children table independently via e.g. a ChildRepository using the Parent Id]
b) Should avoid loading the whole child collection into memory (ideally the oldest child query should be processed by the DB)
This seems something that should be both possible and easy, but I don't see an obvious way of achieving it. Probably I am missing something?
I'm using NHibernate 2.1, so a solution for that would be great, although will be upgrading to 3 soon.

I would create a specialized method on your repository, which returns the oldest child of a given parent.

You could map OldestChild using a Formula. Take a look at this to map a class to a formula: http://blog.khedan.com/2009/01/eager-loading-from-formula-in.html

Related

Coldfusion - ORM removing child objects

I'm trying to nail down the specifics of removing a child in an one-to-many relationship in CF using ORM. I've posted a small test app here:
https://github.com/pnahtanoj/cfrelationship
Regarding the removeChildren() function on ln47 of create.cfm - if I dump the parent object before and after, I see that the children have been removed. However, they are still in the DB after the close of the transaction. Not sure what I'm missing.
Using CF10, MySql 5.something...
Because you set inverse to true on the many side, that means only the child side is tracked by Hibernate.
You can set all the child's parent to null.
public void function removeChildren() {
transaction {
var children = getChilds();
for (var c in children)
c.setParent( javacast('null','') );
}
arrayClear(variables.childs);
}

cached collection not being invalidated by Nhibernate

I have two objects - ContentPage, which has a collection of ChildLinks.
ContentPage
-----------
ID
Title
ChildLink
----------
ID
ParentPageID [ContentPage]
ChildPageID [ContentPage]
Priority
The ContentPage.ChildLinks property utilises the 2nd level cache. I am using Fluent NH to configure Nhibernate, and using Nhibernate 3.1. Cache is set as 'Read-Write' both for the collection, and the 'ChildLink' class.
I've noticed that whenever I delete a ChildLink, the collection cache is not being invalidated. Thus, when I call the ContentPage.ChildLinks, I get an error:
no row with the given identifier exists
I've turned off the cache, and it works well. Shouldn't the cache be automatically invalidated? I am using SysCache as the cache provider, and MySQL as the database.
Thanks in advance!
I had the same problem and I can across the following article which solved my problem:
Inverse Mapped Collections and NHibernate's Second-Level Cache
Basically if you have mapped your collections as inverse, when you delete the child item you also have to make sure to explicitly remove it from the parent collection or the cache state will be invalid after you delete the child. The first thing to check is if the relationship really needs to be inverse.
Assuming inverse is necessary or desired, and using your example:
Instead of only something like:
Session.Delete(ChildLink);
You have to do:
ContentPage.ChildLinks.Remove(ChildLink);
ChildLink.ParentPage = null;
Session.Delete(ChildLink);
You also might need to explicitly save your ContentPage object at this point as well, it depends on your Session flush settings.
I use methods on my entities for managing such inverse relationships, for example:
public ChildLink
{
public ContentPage ParentPage {get;set;}
public void AddToPage(ContentPage addTo)
{
addTo.ChildLinks.Add(this);
this.ParentPage = addTo;
}
public void RemoveFromPage()
{
ParentPage.ChildLinks.Remove(this);
this.ParentPage = null;
}
}
And then when deleting a child object:
ChildLink.RemoveFromPage();
Session.Delete(ChildLink);

NHibernate: How to save a new entity without overwriting the parent:

I'm wondering what the best design would be for persisteing a new child entity with NHibernate without accidentally overwriting the parent in the database.
The problem I have is that the child entity will look something like this:
class Child
{
Parent Parent;
// other fields
}
My problem is that the child has been supplied from the UI layer along with the ID of the parent, and that means that the Parent ref is basically uninitialized: It will have the ID populated but everything else null - because the only way to populate its fields would be an extra round trip to the database to read them.
Now if I call Session.SaveOrUpdate(child) on NHibernate, what's going to happen with the parent. I don't want NHibernate to cascade save the uninitialized parent since that would just destroy the data in the database. How would people approach this problem? Any best practices?
You must use the session.Load(parentid) to get the aggregate root. In contrast to the session.Get() method, this does not actually fetch any data from the database, it just instantiates a Parent proxy object used to add Child objects to the correct Parent in the DB (eg. get the foreign key correctly).
Your code would probably look something like:
// Set the Parent to a nhibernate proxy of the Parent using the ParentId supplied from the UI
childFromUI.Parent = Session.Load<Parent>(childFromUI.Parent.Id);
Session.Save(childFromUI);
This article explains Get/Load and the nhibernate caches really well
You should probably be working with the aggregate root (probably the Parent) when doing Saves (or SaveOrUpdates etc).
Why not just:
Fetch the parent object using the parent id you have in the child from the UI layer
Add the child to the parents 'children' collection
I think you have to overview your mapping configuration for nhibernate. If you have defined on the reference by the child to the parent that hi has to Cascade all, it will update it!
So if you say Cascade.None he will do nothing. All other are bad ideas. Because you allready has the information of this parent. So why read from db agane?!
If your models looks like this
class Parent
{
}
class Child
{
Parent myParent;
}
and you are trying to set the parent and save the child without having a full parent object, just the ID.
You could try this:
session.Lock(child.myParent, LockMode.None);
before saving, this should tell nhibernate that there are no changes to the parent object to persist and it should only look at the object for the Id to persist the association between Parent and Child

nHibernate Collection Count

I have the following model which I have created and mapped with nHibernate.
Using lazy loading so I don't need to get the Vehicles for the Dealer at the start.
Public class Dealer
{
public virtual string Name { get;set;}
public virtual IList<Vehicles> Vehicles { get;set;}
}
Now let's assume the Dealer has thousands of vehicles.
If I do Dealer.Vehicles.Count then NH will select and pull all the data.
What is the best way to simply get a count? Is there any way in which I can get a count with out declaring A new property dealerCount within the Dealer Class?
Also there is a feature in Hibernate which I believe will be implemented in a newer version of NH called Extra Lazy Loading. Would this solve the problem?
extra lazy loading would issue sql instead of populating the collection for certain operations such as Count or Contains. In fluent mappings its used as:
HasMany(x => x.CollectionProperty).ExtraLazyLoad();
or HBM
<one-to-many lazy="extra" ...
It's only usefull if you have large collections and need the special behavior.
Use count projection (Projections.RowCount)

NHibernate Parent/Child relation

I ve got the following setup:
public class ParentEntity
{
public ICollection<ChildEntity> {get; set; }
}
public class ChildEntity
{
// do i need to the parent here?
}
I managed to save the ParentEntity and cascaded the save to the added child entities which were saved as well. But in the db table the ParentId reference of the child was set to allow NULL. When setting it to NOT NULL the save failes since the ParentId in the child table is NULL.
What's happening there? ;)
When
You should map both sides of the relationship normally, and when you add a child to the parent's collection, you should also set the parent property on the child. Normally you would achieve this by writing a method like this:
public void AddChild(ChildEntity child)
{
this.Children.Add(child);
child.Parent = this;
}
NHibernate persists the ParentId column in the Child table based on the mapped property in the ChildEntity class. The definition of the one-to-many relationship merely allows NHibernate to load the collection from the database based on values in this column
I am having the same issue and need this to either have nHibernate expose the foreign key column, or do it in class via collection.
Problem: nHibernate creates the collection object (IList, for example) and you can not override the or listen to the add events of basic collections.
This becomes an issue only because it is required by the WCF RIA Services framework.