Return an object through a projection request

Is it possible to return an object using a projection request?

I have successfully done this with an SQL query (see below), but cannot find how to do this with a projection query.

Dim sql As String = "SELECT {a.*}, {b.*} FROM a LEFT OUTER JOIN b ON a.pk = b.fk")

' Convert SQL results into entities {a} and {b}
Dim query As IQuery = session.CreateSQLQuery(sql) _
                                  .AddEntity("a", GetType(a)) _
                                  .AddEntity("b", GetType(b))

Return query.List()
+3
source share
1 answer

Yes, you can return objects from projection queries.

If you use the HQL query, you can specify the constructor for this class in the HQL select clause:

IList<Foo> foos = session.CreateQuery(
    "select new Foo(f.Name, f.Value) from Foo f")
    .List<Foo>();

This example requires the Foo class to have a constructor that matches the signature used in the HQL query. I.e:

AliasToBean ResultTransformer, , , . , , , . :

IList<Foo> foos = session.CreateQuery(
    "select f.Name as Name, f.Value as Value from Foo f")
    .SetResultTransformer(Transformers.AliasToBean<Foo>())
    .List<Foo>();

, Foo :

public class Foo
{
    public Foo() { }

    public Foo(string name, double value)
    {
        Name = name;
        Value = value;
    }

    public virtual string Name { get; set; }
    public virtual double Value { get; set; }
}

HQL. , , HQL, AliasToBean Foo .

, , , . . .

Update:

AliasToBean API- Criteria, HQL. , . , :

IList<Foo> foos = session.CreateCriteria<Foo>()
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("Name"), "Name")
        .Add(Projections.Property("Value"), "Value"))
    .SetResultTransformer(Transformers.AliasToBean<Foo>())
    .List<Foo>();
+6

Source: https://habr.com/ru/post/1730200/


All Articles