Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Advantages and disadvantages of multiple DB calls

 
dnyan ginde
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a requirement wherein i need to fetch data from the DB and display it on a jsp. I can do this in the following 2 ways:
1)Fetch all the data in one DB call and display it on the screen.
2)Have multiple DB calls and store the data in session. Then take the data from session and display it on the jsp.

Can anybody tell me the advantages/disadvantages of both the methods mentioned above. Also let me know which method is a best practice.
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by dnyan ginde:
I have a requirement wherein i need to fetch data from the DB and display it on a jsp. I can do this in the following 2 ways:
1)Fetch all the data in one DB call and display it on the screen.
2)Have multiple DB calls and store the data in session. Then take the data from session and display it on the jsp.


Given this scenario, 1 is definitely the preferred approach. Why store data in the session, if you can just get it from the database and display it? Naturally, I'd assume that you were populating some sort of Data Transfer Object (DTO) with the call to the database, storing the DTO in the request, and then forwarding to the JSP which then references the DTO.

The general principle is: Only store objects in the session if the information must persist between requests.

A more difficult question would be: should I:

1-Make multiple calls to the database to retrieve the same data over and over again, or
2-retrieve the data from the database once, store it in the session, and continue to reference it in the session.

In this situation "it depends" is the answer.

Approach number one is generally preferred if:
a) we're talking about a large amount of data. The number of concurrent users a system can handle is significantly reduced if each user needs to store a lot of data in the session. Also, if the Application server has to swap session data in and out of memory, performance is going to degrade.
b) The data could be changed by other users. If another user changes the data that I have in my session, my data is stale, and that's a bad thing.

However, if the data is either read-only or exclusive to a single user, and there isn't too much of it, performance is going to be better with approach number two.
 
dnyan ginde
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Merill that helps a lot...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic