Question

I am working on a program which outputs names and various other details(name, address, id, etc) from an user object. The user object is populated through using JDBC from my db. I have learned how to map a resultset object to my user object and how to display various info(name etc) from this object to the screen.

My query is that i will need to access many objects(sometimes all: for searching, updating) and i think it may be silly to make a connection to the db, receive my resultset and map it to an object every time i need certain information. Instead i thought i would get all rows from the database and map all objects and then put them in an arraylist where i could pick out any particular information i wanted more easily.

Is this a inefficient or bad coding practice? Is there a gaping flaw in this logic?

Was it helpful?

Solution

Caching all the rows in the application has many strong disadvantages:

  • it doesn't scale: what if you have 1 million users? What if every user has 5 orders, referencing 7 products, etc. etc. You'll quickly end up with the full database in memory, and that's not sustainable.
  • it's harder to do correctly: you'll have to deal with several requests reading and modifying the users concurrently. Database transactions do that for you.
  • it forces your app to be the exclusive owner of the database. If any other app (or script, or batch) accesses the database, your app won't be aware of it, will display stale data, and will generate errors because, for examle, it will try to update users that don't exist anymore.

The more you have state in an application, the harder it is to make it correct and fast. Trust your database: it's fast and handles many concurrent accesses correctly. If it starts getting slow, then think about your queries, use appropriate indexes, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top