NHibernate "Errors in named queries" - nhibernate

I have the following named SQL query defined:
<sql-query name="ItemSearch">
<return class="ItemSearchResult">
<return-property name="Item" column="ItemId" />
<return-property name="Distance" column="Distance" />
</return>
SELECT
Items.*,
dbo.DistanceBetween(Latitude, Longitude, :lat, :long) AS Distance
FROM Items
WHERE Contains(Name, :keywords)
ORDER BY Distance ASC
</sql-query>
Whenever I try to run my application, I get the generic error "Errors in named queries: {ItemSearch}". Is there something obviously wrong here?
The ItemSearchResult class is a very simple wrapper class that looks like this:
public class ItemSearchResult
{
public Item Item {get; set;}
public double Distance {get; set;}
}

Do you have a correct .hbm.xml for ItemSearchResult? If you use ItemSearchResult in your query, then you need to have a .hbm.xml for it. Just like entities.

Here is a sample from my code:
The only few things that are different between the NHibernate version and my Hibernate is the auto-import and I would assume the package.
<hibernate-mapping auto-import="true" package="PackageName">
<class name="Name of class to maptop">
<composite-id>
<key-property name="<name of parameter>" type="TYPE"/>
</composite-id>
<property name="COLUMNNAME" type="TYPE"/>
</class>
<sql-query name="queryName">
<return alias="dr" class="Name of class to map to"/>
select columnName as {dr.nameofColumn},
from table
</sql-query>
</hibernate-mapping>
I think the problem that exists in your code is that you did not specifically map out the columns and how they map to your class.
Note: If there are any fields that do not correspond to the NHibernate XML format let me know through the comments. I don't have access to my NHibernate mapping files right now.

Related

NHibernate not calling SQL Server

This method gets called.
public IList<MyStuff> GetMyStuff(Int64 MyStuffId)
{
ICriteria criteria = NHibernateSessionManager.Instance.GetSession().CreateCriteria(typeof(MyStuff));
criteria.Add(Expression.Eq("x", MyStuff));
return criteria.List<MyStuff>();
}
But if I profile SQL Server, I can see that NHibernate doesn't try to access the server.
No errors are thrown. It is just the criteria.List() simply returns 0 rows.
MyStuff is a class
public class MyStuff {
public virtual int Id { get; set; }
public virtual int x { get; set; }
... more attributes ....
public override int GetHashCode() {
return (GetType().FullName + "|" + Id.ToString()).GetHashCode();
}
}
And MyStuff is a HBM mapping:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="false" assembly="MyStuff" namespace="My.Stuff" default-lazy="false">
<class name ="MyStuff" table="dbo.viewMyStuff" dynamic-update="false" lazy="false">
<cache usage="read-only"/>
<id name="Id" column="Id" type="int">
<generator class="native" />
</id>
<property name="x" />
.... other properties
</class>
</hibernate-mapping>
The following works just:
select * from viewMyStuff
NHibernate does just fine with other classes/views in the same project.
In fact if I intentionally typo the "table" in the HBM file to "XviewXMyStuffX" NHibernate doesn't have any problem with the typo. Why is NHibernate simply ignoring the expected attempt to access my database view?
I turns out that the view treats the attribute "x" as a string. But in nHibernate I define it as a Int64. These type differences much be causing the criteria to fail. But without any reported error?
Double check that your query really tries to use the exact class you intenden, and that the mapping also applies to exactly the same class. Beware of classes with same name in different namespace or assembly, for instance. One cause of this type of issue is if you attempt to query for a class that is in fact not mapped in NHibernate - then NHibernate will return en empty result, and not an error.
Oh, and have you tried without the cache-element to rule that out?

Mapping the primary key of the table to the same table in Nhibernate

I have one table names SchoolStricture in which the Primary key is "ID" and one another feild is "ParentStructureEntityID" which stores the primary key of the same table.
The purpose of this table is to create a tree structure. During that parent's id will store in this "ParentStructureEntityID". I am a beginner in NHibernate.
How can i map these two feild in my .hbm.xml file.
Please help me out of this.....
Your xml mapping will be something like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="SchoolStructure" table="SchoolStructure">
<id name="ID">
<column name="ID"/>
<generator class="native" />
</id>
<many-to-one name="ParentStructure" column="ParentStructureEntityID" />
</class>
</hibernate-mapping>
And your class will be:
public class SchoolStructure
{
public virtual int ID {get; private set;}
public virtual SchoolStructure ParentStructure { get; set;}
}
That's of course for starters. You should ideally override GetHashCode and Equals in proper manner. Finally I humbly suggest using mapping by code instead of xml mapping. Good luck!

NHibernate could not resolve property of an inherited property

Why can't NHibernate access a property inherited from an abstract base class. When I try to use the property in a QueryOver in the Where clause I'm getting
could not resolve property: ID of: TheWorkshop.Web.Models.Customer
var customer = Session.QueryOver<Customer>()
.Where(c=>c.ID ==id)
.SingleOrDefault<Customer>();
Intelisense helped me build the query and the solution compiles, so there is an ID property on the Customer class. The ID property on Customer is inherited from an abstract Contact class that in turn inherits from a DomainEntity<T> which exposes a protected field.
public abstract class DomainEntity<T>
{
protected Guid _persistenceId;
//...
}
public abstract class Contact : DomainEntity<Contact>
{
public virtual Guid ID
{
get { return _persistenceId; }
}
public virtual Address Address
{
get { return _address; }
set { _address = value; }
}
//...
}
and in the mapping file
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="TheWorkshop.Web"
namespace="TheWorkshop.Web.Models"
default-access="field.camelcase-underscore"
default-lazy="true">
<class name="Contact" table="Contacts" abstract="true">
<id name="_persistenceId" column="ID" type="Guid" access="field"
unsaved-value="00000000-0000-0000-0000-000000000000">
<generator class="guid.comb" />
</id>
<!-- ... -->
<union-subclass name="Customer" table="Customers">
Following the answer to a similar question I updated to NHibernate 3.3.3-CR1 from NHibernate 3.3.2.4000 but I still have the same issue.
The problem was that NHibernate couldn't infer from my mapping how to resolve the ID property. So although the classes compiled fine and the _persistenceId property on the abstract base class could be accessed through a getter on the implementing classes, because of the mismatch in names between _persistenceId and ID NHibernate wasn't able to follow that.
The (easier) solution was to change my names to match up. There is a harder solution which involves implementing the IProperyAccessor, IGetter and ISetter interfaces and in order to provide a path to pass the string ID in order to use the ClassName access strategy.
The simpler of the two solutions was just to rename _persistenceId to _id (and update all the references to it) so
<id name="_persistenceId" column="ID" type="Guid" access="field"
unsaved-value="00000000-0000-0000-0000-000000000000">
becomes
<id name="Id" column="Id" type="Guid"
unsaved-value="00000000-0000-0000-0000-000000000000">
Note I was also able to drop the access="field" in the updated id mappings

Fetching only base type objects in nHibernate

I'm currently trying to solve a problem. I have a class table inheritance aka table-er-subclass (one main table + several others with additional data). In my app both base object instances and extended objects can exist. Now I want to be able to sometimes fetch only those base objects and sometimes both types. A simple example (both classes are mapped with all of their properties)
public class Base
{
public in ID {get; set;}
public string Something {get; set;}
}
public class Extended : Base
{
public bool NewProp{get; set;}
}
now running hql query "from Base" would fetch both Base and Extedned objects. Is there any way to restrict such behavior to fetch only Base objects?
with HQL you should be able to use the "class" special property:
from Base b where b.class=Base
another approach could be to use plain SQL where you have greater control of what you retrieve.
Anyway check the (N)Hibernate docs.
That's the mapping for the above sample (if there's any error forgive me it must be a typo cause the sample runs)
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping auto-import="true"
default-lazy="false"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:nhibernate-mapping-2.2">
<class name="Base, Test"
table="base">
<id name="ID"
access="property"
column="ID"
type="Int64"
unsaved-value="0">
<generator class="sequence">
<param name="sequence">base_id_seq</param>
</generator>
</id>
<property name="Something"
access="property"
type="String">
<column name="somethin"/>
<joined-subclass name="Extended, Test"
table="extended"
schema="extended">
<key column="id" />
<property name="NewProp"
access="property"
type="Boolean">
<column name="newProp"/>
</property>
</joined-subclass>
</class>
</hibernate-mapping>

NHibernate - map same entity to different tables within the same database

Lets say we have an Employee entity composed of a few other entities, such as a one-to-many addresses and contacts, and a few fields (name, age, etc). We mapped this entity out and can use it just fine, saving each piece out into "Employee", "EmployeeAddresses", and "EmployeeContacts" tables.
However, we use pretty much all of this employee's information for a big calculation and have a separate "EmployeeInput" object composed of the same Address and Contact object lists (i.e. both the Employee and EmployeeInputs object has a list of Address and Contact entities). We need to save of this information when we preform the calculation for later auditing purposes. We'd like to save this EmployeeInput entity to an "EmployeeInput" table in the database.
The problem we're running into is how to save the Address and Contact lists? We'd like to stick them into something like "EmployeeInputAddresses" and "EmployeeInputContacts", but the Address and Contact entites are already mapped to "EmployeeAddresses" and "EmployeeContacts", respectively.
What's the easiest way to accomplish this without creating a new "EmployeeInputAddress" and "EmployeeInputContact" entity and separate mapping files for each (as the fields would literally be duplicated one by one). Put another way, how can we map a single entity, Address, to two different tables depending on the parent object it belongs to (EmployeeAddresses table if it's saving from an Employee object, and EmployeeInputAddresses table if it's saving from an EmployeeInput object).
The easiest way would be to have addresses and contacts mapped as composite elements. That way you could map your collection differently for Employee and for EmployeeInput since the mapping is owned by the container.
For example:
public class Employee
{
public List<Address> Addresses{get; set;}
}
public class EmployeeInput
{
public List<Address> Addresses{get; set;}
}
public class Address
{
public string Street{get;set;}
public string City{get; set;}
}
Would have the folloying mapping:
<class name="Employee" table="Employees">
<id name="id">
<generator class="native"/?
</id>
<list name="Addresses" table="EmployesAddresses">
<key column="Id" />
<index column="Item_Index" />
<composite-element class="Address">
<property name="Street" />
<property name="City" />
</composite-element>
</list>
</class>
<class name="EmployeeInput" table="EmployeesInput">
<id name="id">
<generator class="native"/?
</id>
<list name="Addresses" table="EmployeesInputAddresses">
<key column="Id" />
<index column="Item_Index" />
<composite-element class="Address">
<property name="Street" />
<property name="City" />
</composite-element>
</list>
</class>