0

I'm a new java&vertx user. I want to get the result like follow json format, but when running up the second query result is empty. Can somebody help me?

I want to get the Json data:

[ 
         {
           "id",
           "name",
           "offers":[
              {"id2",
               "name2"},
              {"id2",
                "name2"
               }
           ]
         },
         {
            "id",
           "name",
           "offers":[
              {"id2",
               "name2"},
              {"id2",
                "name2"
               }
           ]
         }
       ]

result is:

[ 
  {
    "id",
    "name",
  },
  {
     "id",
    "name",
  }
]

my code is :

moConn.query("select id, name from test1" 
       , query1 -> {   
            if(!query1.failed() && query1.result().getNumRows() != 0){
               JsonArray  arr = new JsonArray(); 
               query1.result().getRows().forEach(re ->{   
                   moConn.query("select id2, name2 from test2" 
                       ,query2 -> {   
                          if(!query2.failed() && query2.result().getNumRows() != 0){
                           JsonArray arr2 = new JsonArray();
                           query2.result().getRows().forEach(arr2::add); 
                           re.put("offers",arr2); 
                      } 
                  }); 
                 arr.add(re); 
              });
             routingContext.response()
                 .putHeader("content-type",    "application/json; charset=UTF-8")
                 .end(arr.encodePrettily());
         }else    {
             routingContext.response()
                 .putHeader("content-type",    "application/json; charset=UTF-8")
                 .end();
         } 
     });
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zhou Jian
  • 1
  • 1

1 Answers1

0

You're returning the response before the second query result is handled. You need to have a callback once the last query select id2, name2 from test2 is performed and only then call:

routingContext.response()
             .putHeader("content-type",    "application/json; charset=UTF-8")
             .end(arr.encodePrettily());

As a note you should be careful with this since you're are doing what is known as N+1 problem.

Community
  • 1
  • 1
Paulo Lopes
  • 5,845
  • 22
  • 31