Help with HQL: Aggregate (count) - nhibernate

Given the model Activity containing a bag with models of type Report (one to many). I would like to get a list of all activities, containing the number of reports of each activity. This two queries don't lead to any good, the counter is always 1 (which is wrong):
select act, (select count(r) from act.Reports r) from Activity act
Or:
select act, count( elements(act.Reports) ) from Activity act group by act.ActivityId, act.Title
Is it possible to write a proper query in HQL to solve this easy task?
Thx for any tipps!
sl3dg3
Edit:
Following the mappings. Activity:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class
name="Core.Models.Config.Activity, Core"
table="Activity"
>
<!-- primary key -->
<id name="ActivityId" type="Int32" unsaved-value="0" access="property">
<column name="ActivityId" not-null="true"/>
<generator class="identity" />
</id>
<!-- Properties -->
<many-to-one name="Title" fetch="join" cascade="all"/>
<!-- One-To-Many Reports -->
<bag name="Reports" inverse="true" fetch="join">
<key column="ReportId" />
<one-to-many class="Core.Models.Report"/>
</bag>
</class>
</hibernate-mapping>
Mapping Report:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class
name="Core.Models.Report, Core"
table="Report"
>
<!-- primary key -->
<id name="ReportId" type="Int32" unsaved-value="0" access="property">
<column name="ReportId" not-null="true"/>
<generator class="identity" />
</id>
<!-- Properties (shortened - there are more many-to-one and one bag -->
<property name="Created" />
<many-to-one name="Activity" column="ActivityId" />
</class>
Class Activity:
public class Activity
{
public Activity()
{
Title = new Translation();
}
public virtual int ActivityId { get; set; }
public virtual Translation Title { get; set; }
public virtual IList<Report> Reports { get; set; }
}
Class Report:
public class Report
{
/// <summary>
/// HNIBERNATE ONLY
/// </summary>
public Report()
{ }
/// <summary>
/// Init Report
/// </summary>
public Report(User author)
{
// ... Shortened
Activity = new Activity();
}
public virtual Activity Activity { get; set; }
}

What you want to achieve is something like this in SQL:
select
act.*,
(select count(*) from Reports rep where rep.id = act.reportId)
from Activity act
It would be easiest using size(), but unfortunately this is not working:
select act, size(act.Reports)
from Activity act
According to the docs, size is not available in the select clause. Interestingly, it actually works with .size, but not with size(), which should actually be equivalent:
select act, act.Reports.size
from Activity act
It may be worth a feature request to also make the function syntax (size()) working.
The officially working group by syntax is cumbersome, because you need to group by all mapped Activity properties:
select act, count(*)
from Activity act left join act.Reports rep
group by act.id, act.Name, act.Whatever
So I tried finally this variant and it seems to be exactly what you need:
select act, (select count(*) from act.Reports)
from Activity act

Your first HQL query has the wrong syntax. Try this instead:
select act, (select count(*) from act.Reports) from Activity act
Your second HQL query cannot work, because you would need all the columns in the GROUP BY clause. Try this instead:
select act.ActivityId, act.Title, count( elements(act.Reports) )
from Activity act
group by act.ActivityId, act.Title
Edit:
Ah, I think this might be the bug:
<bag name="Reports" inverse="true" fetch="join">
<key column="ActivityId" /> <-- instead of ReportId
<one-to-many class="Core.Models.Report"/>
</bag>

Related

nhibernate many-to-many mapping three tables. jumpstart

I am trying to get this solved but can't so far. all kind of errors.
These are my db tables
Person (personID, name, age)
Role (roleID, roleName)
PersonRoles(personRolesID, personID, roleID)
this is my domain class
public Person
{
public virtual Roles RolesForThisPerson {get;set;}
public virtual string Name {get;set;}
public virtual int Age {get;set;}
}
public Roles
{
public virtual IList<string> RoleList {get;set;}
}
I am totally lost on how to approach this. I am so confused about sets, bags, lists... i don't even know where to start.
Anybody can give me a little push here?
thanks
Let's keep the DB schema as it is and adjust the C# domain classes first:
public class Person
{
public virtual string Name {get;set;}
public virtual int Age {get;set;}
public virtual IList<Role> RolesForThisPerson {get;set;}
}
public class Role
{
public virtual string RoleName { get; set; }
}
Now basic mapping for these two entities into defined tables:
<class name="Person" table="Person" lazy="true">
<id name="ID" column="personID">
<generator class="native" />
</id>
<property name="Name" not-null="true" />
<property name="Age" not-null="true" />
<!-- placeholder for roles -->
</class>
<class name="Role" table="Role" lazy="true">
<id name="ID" column="roleID">
<generator class="native" />
</id>
<property name="RoleName" not-null="true" />
</class>
And now we can use the <idbag> mapping and extend the Person class mapping this way:
<idbag name="RolesForThisPerson" batch-size="25" table="PersonRoles"
inverse="true" lazy="true" cascade="none" >
<collection-id column="personRolesID" type="System.Int32" >
<generator class="native" />
</collection-id>
<key column="personID" />
<many-to-many class="Role" column="roleID" />
</idbag>
The <idbag> can profit from the fact, that even the pair table has its own identifier. Cascade is set to none, expecting that roles are in the system, and users are only assigned to them (removed from). Attribute batch-size will effect how many SELECT statements will be executed when fetching the lazy roles collection.

NHibernate one-to-many foreign key is NULL

I have a problem with NHibernate. What i am trying to to is very simple:
I have two Classes. UserTicket and UserData. A UsertTicket has some UserData and a UserData belongs to one UserTicket:
public class UserData{
public virtual int Id { get; set; }
public virtual String PDF_Path { get; set; }
}
public class UserTicket
{
public virtual int Ticketnr { get; set; }
public virtual IList<UserData> UserData { get; set; }
}
And here the mappig xml:
<class name="UserTicket" table="UserTicket">
<id name="Ticketnr">
<generator class="identity"/>
</id>
<bag name="UserData" inverse="true" cascade="all-delete-orphan" lazy="false">
<key column="FK_Ticketnr" not-null="false"/>
<one-to-many class="UserData" />
</bag>
</class>
<class name="UserData" table="UserData">
<id name="Id">
<generator class="identity"/>
</id>
<property name="PDF_Path" />
</class>
When i run it, it works, but the column FK_Ticketnr in the DB-Table of UserData is always = NULL.
Someone told me i have to make a back link from my Child (UserData) to the Parent-Class. But i can not figure out how to do so. How do i get Hibernate to write the value of the Primary-Key (Ticketnr) of UserTicket into FK_Ticketnr?
Thanks in advance
Remove inverse="true" on your bag. That is telling NHibernate that the relationship is managed from the UserData mapping. Since you don't have a back reference, it is never persisted. The other option is to put a parent reference on UserData, but I wouldn't recommend it if you don't need it.
The alternative is the following...
public class UserData
{
// Keep your other properties, add this one too...
public virtual UserTicket Ticket { get; set; }
}
Modify your mapping file like this...
<class name="UserData" table="UserData">
<id name="Id">
<generator class="identity" />
</id>
<property name="PDF_Path" />
<many-to-one name="Ticket" column="FK_Ticketnr" />
</class>
Keep the inverse="true" on the bag.
If you go with this approach, you will need to set Ticket on your UserData objects when you add them to the UserData bag. In other words, you need to maintain both sides of the relationship. You could do this manually or you could try to automate it a little with with methods or constructors.

How to map this class in NHibernate (not FluentNHibernate)?

Suppose I have a database like this:
This is set up to give role-wise menu permissions.
Please note that, User-table has no direct relationship with Permission-table.
Then how should I map this class against the database-tables?
class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool? IsActive { get; set; }
public IList<Role> RoleItems { get; set; }
public IList<Permission> PermissionItems { get; set; }
public IList<string> MenuItemKeys { get; set; }
}
This means,
(1) Every user has some Roles.
(2) Every user has some Permissions (depending on to Roles).
(3) Every user has some permitted MenuItemKeys (according to Permissions).
How should my User.hbm.xml look like?
Roles and Permissions are likely to be accessed a lot in the application. They are very likely to be in the second level cache, which means we can expect to efficiently iterate the User.RoleItems and Role.Permissions.
This has the advantage that we can generally expect to perform no queries when iterating those collections.
You could map the classes as follows.
The properties User.PermissionItems and User.MenuItemKeys are derived from the persistent entities, and thus do not appear in the mappings.
<class name="User" table="user">
<id name="ID">
<generator class="native"/>
</id>
<property name="Name"/>
<property name="Username"/>
<property name="Password"/>
<property name="IsActive"/>
<bag name="RoleItems" table="userrole" lazy="true">
<key column="userid" />
<many-to-many class="Role" column="roleid"/>
</bag>
</class>
<class name="Role" table="role">
<id name="ID">
<generator class="native"/>
</id>
<property name="RoleName"/>
<property name="IsActive"/>
<bag name="Permissions" table="permission">
<key column="roleid" />
<one-to-many class="Permission"/>
</bag>
</class>
<class name="Permission" table="permission">
<id name="ID">
<generator class="native"/>
</id>
<property name="MenuItemKey"/>
</class>
I would make the 2 additional lists you had on User into derived enumerations. If they were lists, there is no unambiguous way to insert into them since you cannot know to which role the value applies. Also, a Role is not owned by a User.
Update: now using Diego's improved version of these properties.
class User
{
public virtual IEnumerable<Permission> PermissionItems
{
get {
return RoleItems.SelectMany(role => role.PermissionItems);
}
}
public virtual IEnumerable<string> MenuItemKeys
{
get {
return RoleItems.SelectMany(role => role.PermissionItems,
(role, permission) => permission.MenuItemKey);
}
}
}
The mapping posted by Lachlan is the best alternative. You could use queries that perform all the joins for each collection, but that'd make them read only for practical purposes.
There is a much easier way to implement the property code, however, that might help you decide:
public IEnumerable<Permission> PermissionItems
{
get
{
return RoleItems.SelectMany(role => role.PermissionItems);
}
}
public IEnumerable<string> MenuItemKeys
{
get
{
return RoleItems.SelectMany(role => role.PermissionItems,
(role, permission) => permission.MenuItemKey);
}
}
Here's a link: Chapter 6. Collection mapping
Here's another useful link: Chapter 7. Association Mappings
EDIT
After having reasearched for an entire evening, I came to the following conclusion:
Considering NHibernate Best Practices, what you wish to do is no good;
Don't use exotic association mappings.
Good usecases for a real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, we think that most associations are one-to-many and many-to-one, you should be careful when using any other association style and ask yourself if it is really neccessary.
As a programming philosophy, I prefer to keep it simple than having to write clever code where even me would no more understand what I wrote after a certain time;
Plus, I even considered using the subquery element of association mapping which would have worked if I would have found a way to parameterize it, if it is doable, but it seems it won't let me parameterize the query with the User instance's Id property value;
In the optic of a well designed OO model, a child being aware of his parent's properties is fine, but a parent accessing a child's property makes no sens - design smell;
As I may understand considering the context exposed the benefits of having permissions or MenuItemKey values accessible from the User directly, I suggest the following solution:
Create yourself a user defined dataview which will hold the values related to the MenuItemKey Permission attribute gotten through the Roles the User is a member like so:
CREATE VIEW udvUsersPermissions AS
SELECT UR.UserID, P.ID as N'ID', P.MenuItemKey
FROM Users U
INNER JOIN UsersRoles UR ON UR.UserID = U.ID
INNER JOIN Roles R ON R.ID = UR.RoleID
INNER JOIN Permissions P ON P.RoleID = R.ID
GO
Then, map it according in you User.hbm.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="User" table="Users">
<id name="Id" column="ID">
<generator class="identity"/>
</id>
<property name="Name" length="100"/>
<property name="UserName" length="10" not-null="true"/>
<property name="Password" length="10" not-null="true"/>
<property name="IsActive" not-null="true"/>
<list name="Roles" table="UsersRoles" access="private-property" lazy="true">
<key column="UserID" foreign-key="FK_UR_U"/>
<list-index column="UserID"/>
<many-to-many class="Role" column="RoleID" />
</list>
<!-- Here mapping Permissions granted to User. -->
<list name="Permissions" table="udvUsersPermissions" lazy="true">
<key column="UserID"/>
<list-index column="MenuItemKey"/>
<many-to-many column="ID" class="Permission"/>
</list>
</class>
</hibernate-mapping>
And here, I will let you know about the subselect solution, in case it works the way I didn't expect it to.
<list name="Permissions" lazy="true">
<subselect> <!-- see section 7.6, Chapter 7 - Association mappings -->
select U.ID, P.ID, P.MenuItemKey
from Users U
inner join UsersRoles UR ON UR.UserID = U.ID
inner join Roles R ON R.ID = UR.RoleID
inner join Permissions P ON P.RoleID = R.ID
group by U.ID, P.ID, P.MenuItemKey
order by P.MenuItemKey
</subselect>
<key column="U.ID"/>
<list-index column="P.MenuItemKey"/>
<many-to-many class="Permission" column="P.ID"/>
</list>
Now, I hope I brought enough details so that it helps you achieve what you want to do or either get on track. =)

<map> with <index-many-to-many> won't save in NHibernate

I have the following mapping:
<?xml version='1.0' encoding='utf-8'?>
<hibernate-mapping
assembly='Core'
namespace='Core.Models'
xmlns='urn:nhibernate-mapping-2.2'>
<class name='Basket'>
<id name='Id'
column='id'>
<generator class='native'/>
</id>
<property name="ExternalId" />
<map name="Items" table="BasketItems" cascade="save-update">
<key column="BasketId" />
<index-many-to-many class="Product" column="ProductId" />
<element column="Quantity" type="System.Int32" />
</map>
</class>
</hibernate-mapping>
This is what the Items collection looks like:
public virtual IDictionary<Product, int> Items { get; private set; }
And I have an Add method like so:
public virtual void Add(Product product, int quantity)
{
if (Items.ContainsKey(product))
Items[product] += quantity;
else
Items.Add(product, quantity);
}
Then the client code looks a bit like this:
var basket = new Basket();
basket.Add(session.Load<Product>(productId));
session.SaveOrUpdate(basket);
Now, the issue is that this client code does save the Basket to the basket table, but does not save any items to the BasketItems table (I'm using SQL Server 2005). However, this test against an in-memory db passes:
[Test]
public void Can_save_basket_with_products() // Passes!!!
{
var b = new Basket();
b.Add(_savedProduct);
_session.SaveOrUpdate(b);
_session.Flush();
_session.Evict(b);
var fromDb = _session.Load<Basket>(b.Id);
Assert.AreNotSame(b, fromDb);
Assert.IsTrue(fromDb.Items.ContainsKey(_savedProduct));
}
Any ideas on why it won't save when I'm against my actual DB? What am I missing?
Note: I translated my entities for this example, I hope it's still understandable even if I left something in portuguese ;-)
Well, found out that I was missing the Flush in my client code. I'm using Castle Monorail and the NHibernate Facility, so it looks as though NH Facility does not flush upon session closing. At least not in a web scenario. I'm assuming the session IS being closed after each request.

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>