NHibernate mapping with custom loader doesn't work - sql

I have a class mapped with NHibernate and I'm trying to use a custom sql-query for loading. Special thing is that it uses a composite-id but I would expect that that's not a problem here.
Here's a simplified version of the mapping:
<class name="Person" mutable="false">
<composite-id>
<key-property name="PropertyA" column="propA" type="int" />
<key-property name="PropertyB" column="propB" type="string" />
</composite-id>
<property name="PropertyC" column="propC" type="datetime" />
<loader query-ref="loadPersons" />
</class>
<sql-query name="loadPersons">
<return class="PV" />
<![CDATA[
SELECT propA, propB, propC FROM MyPersons
]]>
</sql-query>
The problem is that the loader is completely ignored. The query sent to the database is completely generated as if the <loader> element would not be there:
SELECT this_.propA, this_.propB, this_.propC FROM Person this_
This obviously results in the error: table or view does not exist (because 'Person' is just our clean name).
Anyone knows if this is related to the composite-id or is there another reason why loader would be ignored?
Please note that there may be an error in returning the data as well. I've seen there's a special alias-syntax for that but I can't figure that out before the loader is actually doing something...

I know this is a very old question, but I was looking for the answer and came up with something. You use a query, wrapped in parentheses, as the table. It's a little ugly, but it works for me:
<class name="Person" mutable="false" table="(SELECT propA, propB, propC FROM MyPersons)">
<composite-id>
<key-property name="PropertyA" column="propA" type="int" />
<key-property name="PropertyB" column="propB" type="string" />
</composite-id>
<property name="PropertyC" column="propC" type="datetime" />
</class>

Related

NHibernate Mapping a sublass property to another object via foreign key

I am working on an existing data structure that is not perfect and I have an inheritance mapping issue to solve.
I am using a table per hierarchy and have subclasses with discriminators set up. However the subclassed properties are foreign keys back to other tables. How do I set up my subclass mapping so that when I query the fk property I get an object rather than null? Is this even possible?
My current Mapping
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MVC3" namespace="MVC3.Models">
<class name="Image" table="Images">
<id name="Id" column="ImageId">
<generator class="identity" />
</id>
<discriminator column="ImageType" />
<property name="Url" column="Url" not-null="true" />
<property name="Caption" column="Caption" />
<subclass name="AupairImage" discriminator-value="AupairImage">
<join table="Aupairs" inverse="true">
<key column="AupairId" />
<many-to-one name="Aupair" column="AupairId" class="Aupair" />
</join>
</subclass>
<subclass name="FamilyImage" discriminator-value="FamilyImage">
<join table="Families" inverse="true">
<key column="FamilyId" />
<many-to-one name="Family" column="FamilyId" class="Family" />
</join>
</subclass>
I would have like to add an entity diagram but I cannot post images yet :0(
But the foreign keys AupairId and FamilyId link off back to two other tables and are of the type int 32
I know it would be better to restructure the Aupair And Family entities to have a hierarchy to get rid of the one in images but this would be a last resort due to existing code.
Thanks in advance any help appreciated from you mapping experts....
Realised what I was doing wrong after taking a second look, should have just used a Many-To-One under the Subclass with a defined column
<subclass name="MVC3.Models.FamilyImage, MVC3" discriminator-value="FamilyImage">
<many-to-one cascade="all" class="MVC3.Models.Family, MVC3" name="Family">
<column name="FamilyId" />
</many-to-one>
</subclass>

Inheritance: Criterion on entity type and sub class properties

I have a inheritance hierarchy which I have mapped in NHibernate using Table-per-class. My mappping file looks like the one below (lots of properties omitted).
To query this hierarchy, I am building a dynamic DetachedCriteria for Message based on filter input from the user. Messages (of any type in the hierarchy) should be returned to the user in one list.
I would like to build a criteria based on the type of message, ie. the user could specify to get all messages of type SMSMessage or EmailMessage with a ReceivedDate > '2009-01-01'. How would I go about to do that?
In the same query, the user could specify that if the Message is an InternalMessage, it should have Priority = 2. How would I specify such type-specific predicates?
All this is possible to do in LINQ, so I am hoping I can do it in NHibernate as well.
<class name="Message" table="Message" abstract="true" discriminator-value="null">
<id name="MessageId">
<generator class="identity" />
</id>
<discriminator column="Type" type="byte" />
<property name="ParentId" />
<property name="ReceivedDate" />
...
<subclass name="SMSMessage" discriminator-value="0">
<property name="Text" column="Text" />
...
</subclass>
<subclass name="MMSMessage" discriminator-value="1">
<property name="Subject" />
...
</subclass>
<subclass name="EmailMessage" discriminator-value="2">
<property name="BodyPlainText" />
...
</subclass>
<subclass name="InternalMessage" discriminator-value="4">
<property name="Priority" />
...
</subclass>
</class>
I kind of figured this out myself, but in the end I ended up reverting to pure SQL since I hit too many roadblocks with HQL/Criterias. Anyways, I can share how I did this.
Maybe not pretty, but I solved it by adding the discriminator column as a regular property to the top level class in the hierarchy (Message) and employed restrictions against that column.
It turns out that you can specify restrictions against properties for subclasses even in the top-level query, so this was easier than I thought. It was just a matter of specifying the restrictions.

NHibernate doesn't delete db record when object is set to null?

I have two classes: Family and Address.
A family has a physical address and a mailing address.
The mapping file for Family looks like:
....
<id name="Id" column="Id" type="Int32" unsaved-value="0">
<generator class="native"></generator>
</id>
<many-to-one name="PhysicalAddress" class="Address" column="PhysicalAddressId" cascade="all" unique="true" />
<many-to-one name="MailingAddress" class="Address" column="MailingAddressId" cascade="all" unique="true" />
...
The mapping file for Address looks like:
...
<id name="Id" column="Id" type="Int32" unsaved-value="0">
<generator class="native"></generator>
</id>
<property name="StreetAddress1" column="StreetAddress1" />
<property name="StreetAddress2" column="StreetAddress2"/>
<property name="City" column="City" />
<property name="State" column="State" />
<property name="ZipCode" column="ZipCode" />
...
(Note that Family-PhysicalAddress and Family-MailingAddress are one-to-one relationships.)
What I would like to happen is that when I execute
aFamily.MailingAddress = null;
session.Save(aFamily);
session.Flush();
I expect NHibernate to automatically delete the mailing address record from SQL Server for me.
BUT, that doesn't happen. NHibernate does not delete the address record from SQL Server.
Is there any way I can make it work?
Thank you!
This behaviour isn't supported by NHibernate. Of course the problem is that you probably don't have access to the NHibernate session in your domain logic where the change is made.
One possible -- though admittedly not ideal solution -- is to simply run another process to clean up orphaned entities.
Here is a discussion of this scenario:
http://colinjack.blogspot.com/2008/03/nhibernate-gotchas-orphans-and-one-to.html
And a link to a ticket on the issue:
https://nhibernate.jira.com/browse/NH-1262
Unfortunately NHibernate currently does not support automatic deletions of orhphans for many-to-one (Hibernate v3 in Java does support it). It is only supported on lists (cascade="all-delete-orphan").
What you can try to do is to use component mapping. Maybe it is possible to embed many-to-one into a component.
But I think it would better to explicitly delete the related object.

Odd save behaviour with NHibernate and Rhino Repositories

I am experiencing some odd behaviour with NHibernate. I'm retrieving a list of Learners from a repository, updating them as necessary, the odd thing is when I save the first one, the changes made to all the learners are being commited to the database.
[Transaction]
public void UpdateLearner(Learner learner)
{
//UnitOfWork.CurrentSession.Save(learner);
}
Any ideas why? I dont have caching enabled. I know its something to do with the transaction as the changes get persisted even with the call to the save method commented out.
This is my mapping:
<class name="Learner" table="ILR_Learner">
<id name="Id" column="ILRLearnerID">
<generator class="native" />
</id>
<property column="LastWarning" name="LastWarning" type="DateTime" />
<property column="Submitted" name="SuccessfulSubmission" type="DateTime" />
<join table="vwLearnerLSCUpload">
<key column="ILRLearnerID" foreign-key="ILRLearnerID"/>
<property column="Dog" type="DateTime" name="Dog"/>
</join>
<join table="Learner">
<key column="Id" foreign-key="ILRLearnerID"/>
<property column="Food" name="Food" type="String" length="20" />
</join>
</class>
When updating entities, changes are tracked automatically. So when the transaction is committed all changed entities are persisted. No need to call:
Session.Save(entity);
See this Question.
To disable change tracking per entity you have to evict the entity from the session:
Session.Evict(entity);
To persist any changes, you would then call:
Session.Update(entity);

Use two joined subclasses in nhibernate

Ok, new to nhibernate and I am working on a project that has already fully implemented it.
Scenerio: One class (Person) has two joined subclasses (RoleA and RoleB).
What I need is that a given person can actually be both in RoleA and RoleB. How, when given a person that is already created and in RoleA, can I then make them also in RoleB while maintaining the relationships with RoleA?
So, you have something like the following (with Students and Teachers taking the place of RoleA and RoleB):
<class name="Person" table="Persons" >
<id name="Id" column="PersonID">
<generator class="native" />
</id>
<property name="Name" column="Name" not-null="true" />
<joined-subclass name="Student" table="Students">
<key column="PersonID" />
<property name="Grade" column="Grade" not-null="true" />
</joined-subclass>
<joined-subclass name="Teacher" table="Teachers">
<key column="PersonID" />
<property name="ClassName" column="ClassName" not-null="true" />
</joined-subclass>
</class>
If that is the case, your best bet is to use a one-to-one mapping to accomplish the same thing. Here is a good reference: http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-onetoone
This person had a similar problem as you, and ended up going with the one-to-one mapping option:
http://groups.google.com/group/nhusers/browse_thread/thread/1d83e0cd3c2bf58f