My question is: where do I put this cache? I can put it on the Article Class (in the DTO), or I can put it in the DAO class.
As others have noted, this sounds really like reinventing the wheel. But let's look at both cases anyway, so that you better understand how ORM works.
If you save a category in an article , the same category will be loaded again and again when accessing 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 be useful for the cache, but you also need to take care to update the cache when the category has changed.
saveCategory( Category c ) { cache.put( c.id, c ); <save in database> }
The problem with this approach is that (1) the cache can grow over time and (2) that an external update in the database will never be reflected unless you have a timeout mechanism or a way to clear the cache.
Actually, ORM, such as Hibernate, has three levels of caching:
- The essence itself . When a category is loaded with laziness, it is stored in the article object for subsequent direct access.
- First level cache . This is the cache of the current session / transaction. The same object will not be loaded twice, but retrieved from the cache.
- 2nd level cache . This is the cache in all sessions / transactions. This corresponds to the option to cache the value in the DAO. The second-level cache is sometimes more complicated due to the reasons I mentioned above.
I hope you see the best disadvantages / advantages of each type of cache. For more information, check out the popular ORM documentation. Abstracts are general and well-documented.
source share