1

我是 stackoverflow 和 Apache Camel 的新手。我试着写一个可以理解的描述我的问题。

我的目标是从由父表中的 1 个条目和子表中的几行组成的数据库(mysql)中读取分层数据,并将这些数据转换为 pojo。子目标:不编写太多自定义代码并使用蓝图 xml。

由于我找不到适合这个问题的 EIP,所以我在这里列出了我迄今为止的方法:

1.通过连接查询选择数据

select * from parentTable join childTable on childTable.parentId=parentTable.id

这意味着编写一个自定义处理器将结果转换为 pojo,因为每次父属性都会为每个结果行获取选择结果。由于我试图避免编写自定义处理器,因此我尝试了以下方法:

2. 选择查询返回具有正确结构的 JSON 以转换为 pojo

select json_object(
      'parentProperty1', parentProperty1
    , 'parentProperty2', parentProperty2
    , 'children', (select CAST(CONCAT('[',
                GROUP_CONCAT(
                  JSON_OBJECT(  
                          'childProperty1', childProperty1
                        , 'childProperty2', childProperty2
                        )),
                ']')
         AS JSON) 
        from childTable c
        where p.messageId=c.messageId
        )
    ))  
from parentTable p
;

在 mysql shell 上执行查询返回预期的 JSON:

{
    "parentProperty1": "value1",
    "parentProperty1": "value2",
    "children": [
        {
            "childProperty1": "value3",
            "childProperty2": "value4"
        },
        {
            "childProperty1": "value5",
            "childProperty2": "value6"
        }
    ]
}

在骆驼内部运行查询,我遇到了一个问题,我找不到解释或解决方案。

主体在查询执行后具有 JSON,但它被初始查询的片段包围:

[{json_object('parentProperty1', parentProperty1 , 'parentProperty2', parentProperty2 , 'children', (select CAST(CONCAT('[',
={"parentProperty1": "value1", "parentProperty2": "value2", "children": [{"childProperty1": "value3", "childProperty2": "value4"}, {"childProperty1": "value5", "childProperty2": "value6"}]}}]

问题:

  1. 是否有现有的 EIP 可以解决我的问题?
  2. 为什么在我的 2. 方法中没有正确的 JSON?

提前致谢

4

1 回答 1

0

你实际得到的是一个键值对。由于在查询中没有给json_obect指定别名,mysql 会生成一个默认的列名。这就是您在结果中看到的查询片段。

为查询中的 json_obect 添加别名,如下所示:

    select json_object(
      'parentProperty1', parentProperty1
    , 'parentProperty2', parentProperty2
    , 'children', (select CAST(CONCAT('[',
                GROUP_CONCAT(
                  JSON_OBJECT(  
                          'childProperty1', childProperty1
                        , 'childProperty2', childProperty2
                        )),
                ']')
         AS JSON) 
        from childTable c
        where p.messageId=c.messageId
        )
    ) as result  
from parentTable p;

这将返回如下内容:

{result={"children": [{"childProperty1": "value3", "childProperty2": "value4"}, {"childProperty1": "value5", "childProperty2": "value6"}], "parentProperty1": "value1", "parentProperty2": "value2"}}

希望这能解决你的问题

于 2020-07-25T21:58:50.480 回答