Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate DTO mapping

  1. Is it OK to create Mappings for DTO objects and then query them instead of domain? If it is not explain why?
  2. What If i need couple of those dtos?

  • DTos are readonly
  • ID is autogenerated by NH
  • In future these dtos will have set mappings to linked dtos.
  • I use DTO to reduce query size

    <class name="Person" table="`APP_Person`">  
        <property name="FirstName" type="string" length="512" />
        <property name="Age" type="int" /> 
        <property name="SocialNumber" type="int" />
        <property name="PassportId" type="int" />
        <property name="Salary" type="int" />
    </class>
    
    <class  name="PersonDTO" table="`APP_Person`">  
        <property name="FirstName" type="string" length="512" />
        <property name="Age" type="int" />
    </class>
    
like image 747
Vladimir Nani Avatar asked Dec 05 '12 13:12

Vladimir Nani


1 Answers

You don't need to map/persist a DTO object. It's normaly to readonly data and send to other layer of your application (web services, views, etc...).

You can create a query on the Person entity that returns a PersonDTO list. Take a look at SetResultTransformer method. Try somethin like this:

var query = session.CreateQuery("select p.FirstName, p.Age from Person p order by p.FirstName")
                   .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(PersonDTO)))
                   .List<PersonDTO>();

And your DTO:

public class PersonDTO 
{
   public string FirstName { get; set; }
   public int Age { get; set; }
}

The result of the column on the hql query should have the same name of your DTO's properties to NHibernate do the right reflection when construct the DTO and hydrate the object.

Linq

You also can use linq to have a DTO (or a list of DTOs) as a result. For sample:

var query = Session.Query<Person>().OrderBy(x => x.FirstName)
                   .Select(x = new PersonDTO() { FirstName = x.FirstName, Age = x.Age })
                   .ToList();

Look this article: http://gustavoringel.blogspot.com.br/2009/02/creating-dto-in-nhibernate-hql-using.html

like image 91
Felipe Oriani Avatar answered Oct 01 '22 16:10

Felipe Oriani