JegsVala
JegsVala

Reputation: 1867

Execute multiple different different query using spring boot and hibernate

My requirement is to create the multiple threads and execute the query and give the final output like Map<String,List<Object>>;

Map contains table name string and List<Object> is the query output that contains list of tables record.

The requirement:

Above table may have 10 000 queries

I want to create one API for that above query using the spring boot + hibernate.

My problem:

I want to create one solution with multiple threading using JAVA 8.

 @RestController
 public class ApiQueries {
   @RequestMapping(value = "/getAllQueries", method = RequestMethod.GET)     

     public CommonDTO getAllQuery(){

          list=apiQueryService.findAll();
          if(null!=list){
             objectMap= apiQueryService.executeQueryData(list);   //here apiQueryService have one method named is executeQuery()
          }
     } 
 }

I wrote the below logic in that method.

@Override
public Map<String,List<Object>> executeQueryData(List<ApiQueries> 
apiQuerylist, String fromDate, String toDate) {
    addExecutor = new ThreadPoolExecutor(3, 5, 10, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
    List<Object> obj=null;

    Map<String,List<Object>> returnMap=new HashMap<String,List<Object>>();
        try {

            if(session==null) {
                session = sessionFactory.openSession();
            }
            apiQuerylist.forEach(list-> addExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    apiQueryObject = session.createSQLQuery(list.getQuery()).list();    
                    returnMap.put(list.getTableName(), apiQueryObject);
                }

            }));
        }catch(Exception ex) {
            System.out.println("Inside [B] Exception "+ex);
            ex.printStackTrace();
        }finally {
            if(session !=null) {
                session.close();
            }
        }   
        return returnMap;
}

Issue is when i call that api the below code will run in background and that method is return the null object, But in background i will see the list of queries which executes one by one

apiQuerylist.forEach(list-> addExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    apiQueryObject = session.createSQLQuery(list.getQuery()).list();    
                    returnMap.put(list.getTableName(), apiQueryObject);
                }

            }));

Upvotes: 0

Views: 3567

Answers (1)

Sukhpal Singh
Sukhpal Singh

Reputation: 2288

You need to wait for thread pool completion. Something like below after apiQuerylist.forEach should work:

addExecutor.shutdown();
// waiting for executors to finish their jobs
while (!addExecutor.awaitTermination(50, TimeUnit.MILLISECONDS));

Upvotes: 1

Related Questions