假设我有formula
属性的以下映射:
<class name="Planet" table="planets">
<id name="Id" column="id">
<generator class="native" />
</id>
<!-- somefunc() is a native SQL function -->
<property name="Distance" formula="somefunc()" />
</class>
我想获得所有行星,并通过Distance
计算属性订购它们:
var planets = session
.CreateCriteria<Planet>()
.AddOrder(Order.Asc("Distance"))
.List<Planet>();
这被翻译成以下查询:
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc()
所需查询:
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0
如果我使用别名设置投影,它可以正常工作:
var planets = session
.CreateCriteria<Planet>()
.SetProjection(Projections.Alias(Projections.Property("Distance"), "dist"))
.AddOrder(Order.Asc("dist"))
.List<Planet>();
SQL:
SELECT somefunc() as formula0 FROM planets ORDER BY formula0
但它只填充结果中的Distance属性,我真的想避免手动投影到我的对象的所有其他属性(可能还有很多其他属性)。
这可以通过NHibernate实现吗?作为奖励,我想将参数传递给本地somefunc()
SQL函数。产生所需SQL的任何东西都是可以接受的(用子选择替换公式字段等等),重要的是在结果对象中计算Distance属性,并在SQL内按此距离排序。
答案 0 :(得分:4)
这两个在SQL中完全相同。为什么重要?
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc()
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0
编辑,仍然相同:
ORDER BY子句将简单地重复SELECT func调用,无论是否有别名
SELECT Id as id0, somefunc(1, 'fish') as formula0 FROM planets ORDER BY somefunc(1, 'fish')
SELECT Id as id0, somefunc(1, 'fish') as formula0 FROM planets ORDER BY formula0