the query is not taking much time when executing it directly in databaseThat's what I expected (it's just three tables, bound with simple joins). Nevertheless, I'm afraid you still need to start your analysis from the db end - that is, get a DBA, or someone with extensive DB knowledge who can help you to find the cause of the error.
Yes, when we run query in directly database it runs perfectly fine even for single row or many, but when the same is done thru java it says eitherI'm afraid we are running in a loop. First of all, you need to find what SQL command is sent from java to the database. If you say that you execute the same query, using the same login credentials, but you get a different result I don't believe it - there must be something that's been overlooked.