I'm developing a medium Java app, and i'm facing a small problem due to my lack of experience.
I've a custom DAO, which gets "Article" objects from the Database. I've the Article
class, and the DAO has a method called getArticle(int id)
, this method returns an Article
. The Article
has a Category
object, and I'm using lazy loading.
So, when I request for an article's category (Article a = new Article(); a.getCategory();
) the Article
class gets the Category
from the DAO and then returns it.
I'm now thinking to cache it, so when I request multiple times to an article's category, the database is only queried one time.
My question is: where should I put that cache? I can put it on the Article
class (in the DTO), or I can put it on the DAO class.
What do you say?
My question is: where should I put that cache? I can put it on the Article class (in the DTO), or I can put it on the DAO class.
As the others mentioned, it sounds indeed a bit like re-inventing the wheel. But let's consider both cases anyway, so that you will get better understanding of how ORM works.
If you store the category in the article, the same category will be loaded again and again if accessed by different articles.
getCategory() {
if( category == null ) { category = <load from DAO> }
return category;
}
If you store it in the DAO, then all articles with the same category will benefit the cache, but you need to take care to update the cache as well when the category is changed.
saveCategory( Category c ) {
cache.put( c.id, c );
<save in database>
}
Problem with this approach is that (1) the cache may grow large over time, and (2) that external update in the database will never be reflected if you don't have a timeout mechanism or a way to clear the cache.
Actually, ORM such as Hibernate have three levels of caching:
Hope you see better the shortcomings/benefits of each type of cache. For more information, look in popular ORM documentation. Theses issues are common and well documented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With