nhibernate: how to map aggregates - nhibernate-mapping

Good afternoon, I'm trying to learn nHibernate and it's not terribly clear.
I need to get the result of an sql query:
select patient.name,
discipline.description,
sum(patient.enddate - patient.startdate) as totaltime
from treatment
join patient on patient.id = treatment.patientId
join discipline.id = treatment.disciplineId
I don't need to persist the result, just display it.
If I use hql directly:
What objects will it instantiate and return to me? Will it dynamically build a list of objects containing fields identical to the columns in the result set? The docs leave out this information.
If I need to make a mapping:
Do you create a mapping to a 'meta' object or to one of the joined tables (say 'treatment')?
Thanks

This can be achieved by using DTO objects ("data transfer objects"). You create an object that contains only the data you wish to return. Add an initializing constructor. Then your hql can be of the form:
select new mydto( x.value, y.value ) from x join x.y;
It doesn't seem to like using aggregate functions in the object constructor though.

Related

Coldfusion ORM relationship id list

I'm wondering if there is a simple way to get an ID list of all the target objects relating to a source object in a coldfusion component using ORM?
I can see that you can do a collection mapping for one-to-many relationships, but I am using many-to-many relationships. I don't want to have to get the array of objects and then loop over it to get each id.
Is there any built in function or property that could do this?
I think something like the code sample below is a little too heavy since it is getting the whole query and then getting a single column from it.
valuelist( EntityToQuery( object.getRelationalFields() ).id )
Sometimes it doesn't make sense to use ORM, and this is the time. Use the good old <cfquery> for this!
I think ORMExecuteQuery may work for you, something like this:
result = ORMExecuteQuery("select id from Model as m where m.parent.id = :id", {id = 123});
Actual clause format depends on the relationship definition.
In a result you'll have the array of model PKs.

NHibernate: Combining result transformers?

I'm working with the criteria API, querying against a mapping file that I cannot really change. There is a root entity with many child entities joined to it and certain queries have required us to add
criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);
in order to avoid getting duplicate entities when there are multiple SQL result-lines due to the joins. The problem is that now I also want to apply an alias-to-bean transformer, like so:
criteria.SetResultTransformer(Transformers.AliasToBean(typeof(MyDto)));
Using either one of these works great. However, I need to combine them: I want to load only the required columns into a DTO object, and also get only distinct root entities. How can I do this?
To load only required column into DTO you can use projection with DistinctEntityRootTransformer as follows
ICriteria criteria = session.CreateCriteria(typeof(YourEntity));
criteria.SetProjection(
Projections.Distinct(Projections.ProjectionList()
.Add(Projections.Alias(Projections.Property("Property"), "Property")));
criteria.SetResultTransformer(
new NHibernate.Transform.AliasToBeanResultTransformer(typeof(MyDto)));
IList list = criteria.List();

Yii CSqlDataProvider confusion

I am having some trouble understanding CSqlDataProvider and how it works.
When I am using CActiveDataProvider, the results can be accessed as follows:
$data->userProfile['first_name'];
However, when I use CSqlDataProvider, I understand that the results are returned as an array not an object. However, the structure of the array is flat. In other words, I am seeing the following array:
$data['first_name']
instead of
$data['userProfile']['first_name']
But the problem here is what if I have another joined table (let's call it 'author') in my sql code that also contains a first_name field? With CActiveDataProvider, the two fields are disambiguated, so I can do the following to access the two fields:
$data->userProfile['first_name'];
$data->author['first_name'];
But with CSqlDataProvider, there doesn't seem to be anyway I can access the data as follows:
$data['userProfile']['first_name'];
$data['author']['first_name'];
So, outside of assigning a unique name to those fields directly inside my SQL, by doing something like this:
select author.first_name as author_first_name, userProfile.first_name as user_first_name
And then referring to them like this:
$data['author_first_name'];
$data['user_first_name']
is there anyway to get CSqlDataProvider to automatically structure the arrays so they are nested in the same way that CActiveDataProvider objects are? So that I can call them by using $data['userProfile']['first_name']
Or is there another class I should be using to obtain these kinds of nested arrays?
Many thanks!
As far as I can tell, no Yii DB methods break out JOIN query results in to 2D arrays like you are looking for. I think you will need to - as you suggest - alias the column names in your select statement.
MySql returns a single row of data when you JOIN tables in a query, and CSqlDataProvider returns exactly what MySql does: single tabular array representation indexed/keyed by the column names, just like your query returns.
If you want to break apart your results into a multi-dimensional array I would either alias the columns, or use a regular CActiveDataProvider (which you can still pass complex queries and joins in via CDbCritiera).

How can one fetch partial objects in NHibernate?

I have an object O with 2 fields - A and B. How can I fetch O from the database so that only the field A is fetched?
Of course, my real application has objects with many more fields, but two fields are enough to understand the principal.
I am using NHibernate 2.1.
Thanks.
EDIT:
I wish to clarify. I need to fetch objects of type O. Sometimes I will want to fetch complete objects - meaning both A and B fields are set from the database values. But on other occasions, I would like to fetch O objects with just the A field set from the database values.
Use a projection to narrow the result set to the desired column(s) and a result transformer to convert the result into the type that you want.
This will return transient objects rather than persistent entities.
// select some User objects with only the Username property set
var u = session.CreateCriteria<User>()
.SetProjection( Projections.ProjectionList().Add(Projections.Property("Username"), "Username") )
.SetResultTransformer( Transformers.AliasToBean<User>() )
.List<User>();
HQL has a select new construct, which allows you to fetch only a subset of fields. Objects returned, however, cannot be saved back to the DB.
As an alternative, you can create additional classes with a limited set of properties an map those onto table in question.

(N)Hibernate Auto-Join

I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query:
SELECT v1.Id
FROM VIEW v1
LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id
ORDER BY v1.Position
It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names.
You could just perform the select on the original entity and make the association between the two objects "lazy = false". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object.
If you don't want to map "lazy=false" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open.
Update:
I think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.