【问题标题】:Querying Postgres from Grails MVC application从 Grails MVC 应用程序查询 Postgres
【发布时间】:2015-12-10 08:15:31
【问题描述】:
  • 配置的 Datasource.groovy 和 BuildConfig.groovy
  • 在 groovy 服务中查询 Postgres 数据库时需要帮助。

在 postgres 中有一个下表: table structure

需要在 grails 应用程序中编写以下 SQL 查询:

SELECT json_agg(r)
FROM(
SELECT data#>'{"name"}' as program,data#>'{"country"}' as agency,sum(cast(cast(data#>'{"amount"}' as text)as Integer)) as total_amount 
 FROM salary 
 group by data#>'{"name"}',data#>'{"country"}'
 order by program, agency
)r  

【问题讨论】:

  • 需要根据过滤条件从postgres中查询JSONB数据,或者说需要从mongodb迁移到postgres,使用mongo colllection对应的如下schema: id, data (jsonb datatype) .不确定我是否清楚地解释了我的观点..

标签: postgresql grails grails-orm


【解决方案1】:

对不起,我还不能发表评论,因为我没有 50 名声望,所以我在这里留下我的评论。 您是否尝试过在 postgres 中使用 CREATE VIEW 创建视图并使用服务中的简单查询?这就是我对我所做的。从 grails 中以这种方式查询要容易得多。

编辑 - My SQL 服务示例

package com.myApp

import groovy.sql.Sql  //Need to import this 

class SomeService {

    def dataSource //Need it to connect to your database

    def result() {

        def sql = new Sql(dataSource)

        def resultRows = sql.rows('...your SQL statement...')
    }
}


package com.myApp

class SomeController {

    def someService  //Inject your serivce here

    def resultRows = someService.result()  //Call service method here
    [resultRows:resultRows]  //Put the result into a map

}

你可以从你的视图中调用你的结果图。

现在,如果您不想在服务中使用长 SQL 语句,可以在 postgres 中使用 CREATE VIEW sql 语句。

CREATE or REPLACE VIEW result_table as
        (... your SQL statement...);

希望对你有帮助。

【讨论】:

  • 感谢您的建议,但是我们需要在grails代码中编写数据查询逻辑,请建议我们是否可以这样做,或者您可以提供访问数据的代码行从视图...
  • @shubham,我已经包含了我的示例。
【解决方案2】:

使用以下代码,它可以工作...

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/TestDb");
dataSource.setUsername("postgres");
dataSource.setPassword("password");
def sql = new Sql(dataSource)
def resultRows = sql.rows(---SQL Query here---)
return resultRows

需要帮助将上述 JDBC 方法替换为 Hibernate。

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 2016-11-03
    • 2019-04-30
    • 2011-03-24
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多