Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calculate the distance between two locations through HQL in Java

    • 0
    • 4
    • 1
    • 4
    • 0
    • 0
    • 0
    • 0
    • 1.14k
    Comment on it

    Sometimes we need to calculate the distance between two locations. And to save the time of iteration we can get filtered results through query by apply functionality of calculating distance in the query.

    Suppose we have two tables Events and User, and we want to display only those events that fall under the user's geographical area lets say within 50 miles. Both table should have latitude and longitude as columns.

    Write the following code to get filtered data by distance:

    // Here you will pass user's lat/long as argument
    public List<Events> getAllEvents(double latitud, double longitude) {
            List<Events> eventsList = null;
            String hqlQuery = "select a from Events a where a.event&#95;date >= :currentDate and (((acos(sin(((:latitude)*pi()/180)) * sin((a.latitude*pi()/180))+cos(((:latitude)*pi()/180)) * cos((a.latitude*pi()/180)) * cos((((:longitude)- a.longitude)*pi()/180))))*180/pi())*60*1.1515) <=50 ";
            try {
                Query query = sessionFactory.getCurrentSession().createQuery(
                        hqlQuery);
                query.setDouble("latitude", latitud);
                query.setDouble("longitude", longitude);
                eventsList = (List<Events>) query.list();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return eventsList;
        }
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: