播放映射忽略RawSQL Ebean

时间:2018-09-11 09:59:51

标签: java postgresql playframework ebean

我使用的是Play Framework 2.3,在尝试创建自己的sql查询时,我总是在映射忽略方面遇到麻烦。

我不知道我是否应该使用Ebean编写这个复杂的sql查询。

这是SQL查询工作得很好:

 SELECT g.id, 
  concat(g.client_id,'-',trim(to_char(n.number,'099999'))) as reference,
 (
  SELECT sum(total_ttc)
    from global_commission_invoice_line 
  where global_commission_invoice_id= g.id 
 ) as totalTTC  
 from global_commission_invoice g 
 LEFT JOIN invoice_number n on g.invoice_number_id = n.id 
 LEFT JOIN client c2 on g.client_id = c2.id

我尝试用ebean解析它,因为我有一个带有参数的 WHEN 子句。

我的Java代码简要如下。

String sql = " SELECT g.id, " +
        " concat(g.client_id,'-',trim(to_char(n.number,'099999'))) as reference," +
        " (" +
        "  SELECT sum(total_ttc)" +
        "    from global_commission_invoice_line" +
        "  where global_commission_invoice_id= g.id" +
        " ) as totalTTC " +
        " from global_commission_invoice g" +
        " LEFT JOIN invoice_number n on g.invoice_number_id = n.id" +
        " LEFT JOIN client c2 on g.client_id = c2.id";

// Create sql
RawSql rawSql = RawSqlBuilder.parse(sql)
        .columnMapping("g.id","id")
        .columnMappingIgnore("concat(g.client_id,'-',trim(to_char(n.number,'099999')))")
        .columnMappingIgnore("( SELECT sum(total_ttc) from global_commission_invoice_line where global_commission_invoice_id= g.id )")
        .create();

return Ebean.find(models.GlobalCommissionInvoice.class).setRawSql(rawSql)
                .findList()

此映射忽略成功,并且没有错误:

.columnMappingIgnore("( SELECT sum(total_ttc) from global_commission_invoice_line where global_commission_invoice_id= g.id )")

但是这个:

.columnMappingIgnore("concat(g.client_id,'-',trim(to_char(n.number,'099999')))")

返回此错误:

Execution exception[[IllegalArgumentException: DB Column [ concat(g.client_id, '-', trim(to_char(n.number, '099999')))] not found in mapping. Expecting one of [[g.id, concat(g.client_id, '-', trim(to_char(n.number, '099999'))), ( SELECT sum(total_ttc) from global_commission_invoice_line where global_commission_invoice_id= g.id )]]]]

有时候我发现错误,大约是一个空格或一个换行符放错了位置,但我从来不知道如何真正地将它用于复杂的查询,而又不搜索为什么我会出错几个小时。

我应该对这种类型的sql查询使用ebean吗?我在使用映射时会严重忽略吗?

P.S。 :对不起,我的英语,我是法语

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我调试了ebean RawSql类,并使映射与ebean映射匹配。

在每个逗号处

Ebean slice SELECT 语句,因此我的 concat 函数分为三部分。

解决方案:

        // Create sql
    RawSql rawSql = RawSqlBuilder.parse(sqlStringBuilder.getStrStatement())
            .columnMapping("g.id","id")
            .columnMappingIgnore("concat(g.client_id")
            .columnMappingIgnore("'-'")
            .columnMappingIgnore("trim(to_char(n.number")
            .columnMappingIgnore("'099999')))")
            .columnMappingIgnore("( SELECT sum(total_ttc) from global_commission_invoice_line where global_commission_invoice_id= g.id )")
            .create();