Groovy脚本中的两个表查询

时间:2011-12-16 18:02:31

标签: sql hibernate grails join groovy

如何在ProductsController脚本中的grails中处理此SQL查询?注意它的两个表在产品ID上有一个连接。

SELECT p.*,pd.* 
FROM products p, products_description pd 
WHERE p.products_id=pd.products_id
ORDER BY p.products_date_added DESC 

显然我不能这样做:

def all= {
    def a
     a = Products.find("FROM products p, products_description pd 
      WHERE p.products_id=pd.products_id ORDER BY p.products_date_added DESC")
     render a as JSON
}

2 个答案:

答案 0 :(得分:1)

如果您坚持使用自定义SQL查询而不是任何grails动态查找器,则可以使用以下代码:

    def session = sessionFactory.getCurrentSession() // a reference to the sessionFactory is injected in all controllers and services that have a sessionFactory variable defined
     Query query = session.createSQLQuery("SELECT p.*,pd.* 
     FROM products p, products_description pd 
     WHERE p.products_id=pd.products_id
     ORDER BY p.products_date_added DESC");
     def result = query.list()

您必须向控制器添加名为sessionFactory的变量。像这样:

    class ProductsController = {
      def sessionFactory

结果列表将是列表列表。主列表的每个元素都是大小为2的列表,第一个元素作为产品,第二个元素作为产品描述。

答案 1 :(得分:0)

您可以使用Many-to-one and one-to-one关系,让GORM为您处理关联。

class Products {
    ProductsDescription description
    ...
    static mapping = {
        description column: 'products_id'
    }
}

然后,您可以通过引用访问说明:

a = products.listOrderByProductsDateAdded(order: 'desc')
a.description.productsDescription