Create Dynamic Sql or Hql Query - Utopian

in #utopian-io8 years ago

Hello Friends !

I'm going to tell about how to create dynamic query...

If you have multiple attributes to search for a table then how you can create query for it.

kkmk.jpg

Lets start...

Get all the input to check for query add in String array : list[]

    List<Users> users = null;
    String qry = "";
    String list2[] = new String[5];
    list2[0] = "user_name";
    list2[1] = "user_email";
    list2[2] = "user_mobile";
    list2[3] = "user_city";
    list2[4] = "user_country";
    
            int c=0;
    for(int i=0;i<list.length;i++)
    {
        if(list[i]!=null)
        {
                          if(c==0){
            qry+= " where "+list2[i]+"="+list[i];
                            }
        }
        else
        {
            qry+= " and "+list2[i]+"="+list[i];
        }
                  c++;
    }

        users = sessionFactory.getCurrentSession().createQuery("from Users "+qry).list();

Thus you can create the dynamic queries ....

Good Luck !

Hope you like my post...

Sort:  

This post received a 11% upvote from @morwhale team thanks to @ravik2492! For more information, click here! , TeamMorocco! .