HQL in CriteriaQuery using bitwise operators

How to convert this to CriteraQuery:

select n
from TagRegistration t
join t.Tag n
where t.Status & :status > 0
order by count(t.ID) desc
       , n.Name asc
+5
source share
2 answers

Here you can do it using API criteria:

[Flags]
enum Bar{
   A = 0x01,
   B = 0x02,
   C = 0x04
}

var criteria = this.Session.CreateCriteria<Foo>()
            .Add( BitwiseFlags.IsSet( "Bar", Bar.A | Bar.C ) );

through:

public class BitwiseFlags : LogicalExpression
{
    private BitwiseFlags( string propertyName, object value, string op ) :
        base( new SimpleExpression( propertyName, value, op ),
        Expression.Sql( "?", value, NHibernateUtil.Enum( value.GetType() ) ) )
    {
    }

    protected override string Op
    {
        get { return "="; }
    }

    public static BitwiseFlags IsSet(string propertyName, Enum flags)
    {
        return new BitwiseFlags( propertyName, flags, " & " );
    }
}

should generate the following output where where:

 FROM _TABLE
 WHERE  (this_.Bar & 5 = 5)

which should give you the lines with the Bar.A and Bar.C flags (excluding everything else). You can also use it with conjunction and disjunction.

+14
source

Something like that back.

Try something like this.

PropertyProjection projection = Projections.Property("t.ID");
PropertyProjection property = Projections.Property("n.Namn");
ICriteria criteria = session.CreateCriteria<TagRegistration>("t")
                .CreateCriteria("Tag","n")
                .Add(
                        Restrictions.Gt(
                            Projections.SqlProjection("({alias}.ID & 3) as bitWiseResult", new[] { "bitWiseResult" }, new IType[] { NHibernateUtil.Int32 })
                        , 0)
                     )
                .AddOrder(Order.Desc(Projections.Count(projection)))
                .AddOrder(Order.Asc(property))
                .SetProjection(Projections.GroupProperty(projection), Projections.GroupProperty(property))

Pay attention to this part of {alias} .ID and 3), where I inserted a direct value, which is not very good, but it works :)

You could do it better if you had a look at the NHibernate NHibernate test project / Criteria / AddNumberProjection.cs

subQuery, , Hql.

+1

All Articles