NHibernate fetch="join" mapping attribute does not appear to work - nhibernate

Mapping a dictionary with NH. Declaration is as follows:
<hibernate-mapping ...
<map
name="CostsByRole"
table="JobAccountingSnapshotCosts"
lazy="false"
fetch="join"
access="nosetter.camelcase-underscore">
<key column="SnapshotId" />
<index column="RoleCode" type="String" />
<element column="Amount" type="Decimal" />
</map>
</hibernate-mapping>
I am expecting a single SQL query to be generated but instead I get two: a select for the actual object, followed by a select for the contents of the dictionary.
Any ideas?

HQL queries do not consider the values set for fetch in the mapping. You need to specify them exclusively in each HQL query. Its supposedly by design. The fetch attributes value is used only by Criteria queries and by Load/Get.

Assuming it's not a typo on submission, the problem is likely to be the join="fetch" part in your mapping. It should be fetch="join" and since the default for fetch is "select", that would yield your sequential select problem.

Related

How to persist a subset of an object instead of the whole object?

I'm struggling with a NHibernate related problem where I could use some input.
Introduction:
I have a legacy database where the relational concepts have not really been applied.
In the database I have an OrderLine table which contains data for an order lines.
On top of that the table also contains all columns with Order specific information. This could for example be order number of a customer.
E.x. If i have 10 order lines - then I have 10 rows in my OrderLines table and each row has all the Order specific data e.g. order number or customer information.
I did not want to have the above structure in my code so a view was created for Orders so that I could map my Order in NHibernate which then has a set/bag of OrderLines which makes much more sense.
Mapping: (simplified)
<class name="Order" table="[view_Orders]">
<bag name="OrderLines">
</class>
<class name="OrderLine" table="OrderLines" />
The problem:
The complexity of the view makes it impossible to save to the view. When trying NHibernates throws this exception:
NHibernate.Exceptions.GenericADOException: could not insert: XXX ---> System.Data.SqlClient.SqlException: View or function 'view_Orders' is not updatable because the modification affects multiple base tables.
My NHibernate mapping is constructed as an Order object which has a "set or bag" of OrderLine objects. Ideally I would like NHibernate only to persist the set of OrderLine objects instead of the whole object.
Is there a way of achieving this? I have tried locking the object using different lock modes but it did not help me.
You can use mutable="false" to avoid the update and deletes as this article says:
Immutable classes, mutable="false", may not be updated or deleted by the application. This allows NHibernate to make some minor performance optimizations.
To avoid the insert you can use the following statement (Uses the proyection instead an insert command, dont forget use check="none"):
<sql-insert check="none">SELECT 1</sql-insert>
Here is a tested example:
<class name="Order" table="[view_Orders]" mutable="false">
<id name="OrderId" type="System.Guid">
<generator class="guid.comb"/> <!-- Change as you need -->
</id>
<!-- Other properties -->
<!-- <property name="GrandTotal"/> -->
<set name="OrderLines" lazy="true" inverse="true" cascade="all-delete-orphan">
<key column="OrderId"/>
<one-to-many class="OrderLine"/>
</set>
<sql-insert check="none">SELECT 1</sql-insert>
</class>
<class name="OrderLine" table="OrderLine">
<id name="OrderLineId" type="System.Guid">
<generator class="guid.comb"/> <!-- Change as you need -->
</id>
<!-- Other properties -->
<!-- <property name="OrderId"/>
<property name="GrandTotal"/>/> -->
</class>
In case I do understand your issue, the solution is surprisingly simple. We just would mark root object with dynamic-update="true"
<class name="Order" table="[view_Orders]" dynamic-update="true">
...
</class>
And then apply update="false" to every property or reference which we have in that Order class mapped to view:
...
<property name="Code" update="false"/>
...
<many-to-one name="Country" update="false />
But our collection will need the standard, even cascade mapping:
<class name="Order" table="[view_Orders]" dynamic-update="true">
<bag name="OrderLines"
lazy="true"
inverse="true"
batch-size="25"
cascade="all-delete-orphan" >
...
</bag>
... // other stuff is update="false"
</class>
And now code like this would do management of OrderLines, while not executing any updates on the root object Order
var session = ... // get ISession
// load root
var root = session.Get<Order>(123);
// if needed change existing line (pretend there is one)
root.OrderLines[0].Amount = 100;
// add new
var newOrder = ... // new order
root.OrderLines.Add(newOrder);
session.Save(root);
session.Flush();
And that is it. Cascade on the root object is doing what we need, while the update="false" is not updating it...
NOTE: Just interesting note - there is also class and collection
setting mutable="false", but it would not work here... as the
solution mentioned above (it is sad, because that would be more
elegant, but not working as expected...). See:
19.2.2. Strategy: read only
If your application needs to read but never modify instances of a persistent class, a read-only cache may be used. This is the simplest and best performing strategy. Its even perfectly safe for use in a cluster.
<class name="Eg.Immutable" mutable="false">

NHibernate filter on property from many-to-one

I'm trying to use an NHibernate filter to filter on a parent class's property, but I keep getting an error that the multi-part identifier "Parent.Active" could not be bound. My filter-def is:
<filter-def name="useActive" />
My parent class has this in the mapping:
<property name="Active">
<column name="ACTIVE" not-null="true" />
</property>
<bag name="Children" table="CHILDREN" inverse="true">
<key>
<column name="PARENT_ID_IN_CHILD" />
</key>
<one-to-many class="ChildType" />
</bag>
My child class has this in the mapping:
<many-to-one name="Parent" class="ParentTyle">
<column name="PARENT_ID_IN_CHILD" />
</many-to-one>
<filter name="useActive" condition="Parent.Active = 1" />
How can I get NHibernate to check the parent column when filtering?
edit: I'm enabling the filter using mySession.EnableFilter("useActive");. I'm also using LINQ-to-NHibernate, but I don't think that should matter.
The error you're receiving came from SQL Server that can't find the column "Active" on the table "Parent".
Keep in mind that when you're defining a filter the string that you put in the condition will simply be appended in the where condition of the select as is. If you want to filter for that field you must first identify the alias nHibernate use for your SQL query than put that alias instead of "Parent". it coube something like "mytable_0" or something like that.

nhibernate: Class Mapping with no table

I have an entity class that I use to represent the results of an sql-query. The mapping for the class shown below. Yet as far as I can tell nhiberate treats the mapping as if there is a real database table - when in fact there is not. In this case there is nothing in the database that represents this entity at all. I am using this to map a query through, but the same would be true of a view. Is there no way to indicate to nhibernate that there isn't a table represented by the mapping?
<class name="Models.UserTransaction"> <!-- Defaults table name same as Entity even though table doesn’t exist -->
<id name="Id">
<column name="Id" not-null="true" unique="true" />
<generator class="native" />
</id>
<property name="TransType" />
<property name="Date" />
<property name="Amount" />
<property name="Balance" />
</class>
This is the query I am mapping, which uses a user defined table. I couldn't get it working without having a mapping even though the example I copied appeared to.
<sql-query name="UserTransactions">
<query-param name="userId" type="string" />
<return class="Models.UserTransaction" alias="userTx">
<return-property name="TransType" column="TransType" />
<return-property name="Id" column="Id" />
<return-property name="Date" column="TransDate" />
<return-property name="Amount" column="Amount" />
<return-property name="Balance" column="Balance" />
</return>
<![CDATA[
SELECT userTx.[Type] as TransType, userTx.[Id] as Id, userTx.[Date] as TransDate, userTx.[Amount] as Amount, userTx.[Balance] as Balance
FROM dbo.User_AccountStatement(:userId) userTx
]]>
</sql-query>
If you have a db view, you can use nhibernate to map to that, but if all you are doing is storing the projection fields of the query there doesn't need to be a map at all.
How are you querying this data?
if you are using the criteria API, you can use the resultstransformer to map the returned object array to your class. the types have to match between your class that the projection.
if you are using the linq provider you can project directly into your class. so you'd have something like this
from s in Session.Query
where s.some-property== "some-value"
select new your-type
{
some-property-on-your-type = s.some-property,
some-other-property-on-your-type = s.some-other-property
}
There is no need to write a mapping to the database since you aren't mapping to an object in the database.
I guess you should at least specify a view as the tablename of your mapping.
The view should have the same resulting columns as your query (and hopefully return any row that your query could return)
Then you will be able to :
map your properties to your view/SQL query result columns
set your class as mutable="false"
declare your query as a named query (see : http://ayende.com/blog/3948/nhibernate-mapping-named-queries-query-and-sql-query )

NHibernate simple collection of joined-subclass entities

I'm trying to map a set of joined-subclass entities to a parent entity. The SQL being produced by NHibernate seems to be incorrect. Am I missing anything in my mapping? Is there another way I can approach this problem?
<class name="ResultItem" table="result">
<id name="ID">
<generator class="identity" />
</id>
<many-to-one name="Job" column="JobID"/>
<property name="Timestamp"/>
<many-to-one name="User" column="UserID"/>
<joined-subclass name="ResultItemAttachment" table="result_attachment">
<key column="ID"/>
<property name="Comment"/>
</joined-subclass>
</class>
This is the SQL being generated by NHibernate. It seems as if its getting confused between super and sub class members? The only table with JobID is the result table and not result_attachment.
SELECT attachment0_.JobID as JobID1_,
attachment0_.ID as ID1_,
attachment0_.ID as ID26_0_,
attachment0_1_.JobID as JobID26_0_,
attachment0_1_.`Timestamp` as Timestamp26_0_,
attachment0_1_.UserID as UserID26_0_,
attachment0_.`Comment` as Comment33_0_
FROM result_attachment attachment0_
inner join result attachment0_1_ on attachment0_.ID=attachment0_1_.ID
WHERE attachment0_1_.JobID=?;
Thanks in advance
I'm afraid this is currently a bug in NHibernate (in there since 2.1 :|) apperently there is a fix in the current alpha of 3.2
https://nhibernate.jira.com/browse/NH-1747
Possible work around is to manually fetch the bag at runtime. Hardly ideal, other option would be to try and get the alpha version running but running an alpha in a production environment is hardly a great idea.

NHibernate: Where clause on one-to-many relationships doesn't work when column name is ambiguous

It is possible to specify an arbitrary SQL where clause for collection mappings. For example:
<map name="myEntity" where="foo = 1" />
However if the column name is ambiguous for some reason, the sql fails. For example, this can occur if you are trying to use joins for example.
Given that the table aliases are automatically generated, you can't qualify the column name. This makes the feature seem rather silly. Does anyone know if there is a work around?
NHibernate should figure out the correct alias for the property you are referencing. Is foo a mapped property of the item entity type (the item type that is in the map collection) ?
For example this works:
<class name="Category" table="Category">
<id name="Id">
<generator class="guid.comb" />
</id>
<property name="Name" not-null="true" length="255" />
<bag name="ProductList" table="Product" cascade="none" where="Name like '%test%'" fetch="join">
<key column="CategoryId" />
<one-to-many class="Product" />
</bag>
</class>
There is a property on both Category and the Product class named "Name" but nhibernate will in this case use the on defined on the Product class.