2012-04-16 91 views
2

我想使用Gorm检索最近的10个地理定位对象。 为此,我想自定义order()参数,以便使用sql函数的get_distance(longitude,latitude,:longitude,:纬度)。 我一直在为这一整天挣扎,有没有人有提示?Grails:如何使用sql函数自定义顺序?

谢谢!

编辑

我终于成功地做我想要的东西,但有一个非常丑陋的解决方案:

  • 我添加了一个sqlProjection中,我把我的get_distance()函数,并能订购通过它。
  • 添加一个投影会删除对象属性的检索,所以我不得不通过添加属性投影明确地要求它,并且我设法通过内省来做到这一点。
  • 然后我不得不定义它的标准结果转换器给我域实例。

回答

1

如果使用hibernate SQL方言注册您的函数,那么您可以在HQL查询中使用它。例如,把这个在你的引导代码:

import org.hibernate.dialect.function.SQLFunctionTemplate 
import org.hibernate.Hibernate 

def dialect = applicationContext.sessionFactory.dialect 
def getDistance = new SQLFunctionTemplate(Hibernate.INTEGER, "get_distance(?1,?2)") 
dialect.registerFunction('get_distance', getDistance) 

然后你可以在HQL使用它:

Location.executeQuery(
    """ 
     select id, get_distance(latitude, longitude) as distance 
     from Location 
     order by distance 
    """, 
    [], [max: 10]) 
+0

感谢您的快速回答!事情是我需要具有相同的行为,但在_createCriteria()_查询。任何想法 ? – Allan 2012-04-16 16:44:20

+0

我想你可以使用'sqlRestriction'在条件中过滤函数,但我不知道有什么方法可以用它来排序。 – ataylor 2012-04-16 17:06:40

0

我们所做的是以下几点:

  1. 创建与查询任何数据库特定的操作符,但作为视图
  2. 创建一个新的域类对象只映射到视图,从而允许您执行GORM标准查询等
+0

不错的黑客,但我不认为它可以适用于我的情况:我的get_distance()函数需要参数,因为它计算从给定坐标的距离: select * from Location l order by get_distance(l.longitude,l.latitude, :longitude,:纬度) – Allan 2012-04-16 17:00:29

+0

好的..我没有在DB中使用存储过程/函数十多年了,除了第一个解决它之外没有看到任何其他方法..你可以试着从更低级别的Hibernate角度.. http://stackoverflow.com/questions/7183110/hibernate-stored-procedure-result-problem – 2012-04-17 17:12:27