Lazy Loading DTO fields in Spring

I have a project that uses Spring and is broken down into several dozen DAOs and related DTOs. I use JdbcTemplate, but not much more, since this is exactly the level of abstraction that I am pleased with.

I am currently doing lazy loading on my DTOs, putting rather hairy code in their getters.

Basic logic: 1. If the field is not null, return its value and exit 2. Contact the appropriate DAO and select the appropriate DTO 3. Keep them until the next time.

It works great, except that my junior DTOs are associated with a number of DAOs and not so POJOeys.

Another smell of code appears if I put the logic in the DAO, since it will handle both CRUD for its DTOs and Lazy Loading, and, as I understand it, objects should have one responsibility.

I hope there is a relatively simple Spring approach that I can use to enter a Lazy Loader object between the DAO and DTO to achieve this, but any other solution will work for me.

Any ideas?

+6
java spring jdbc lazy-loading
source share
2 answers

It's easier to wrap the DAO around the DAO ... it depends on which part of the model you want to use. DTOs are not usually used to transfer one of them with them, as two or more separate database / Tao calls. In this case, you really want an ORM. Since you are looking for the answer dao ......

Nothing prevents you from tying DAO together to give you one DTO. Then it’s easier to connect the DTO to the DAO. This is not really a service level, it just builds DAO blocks. So you can have PersonDao and TelephoneNumberDao. A person can have more than one phone number, so you can also have PersonModelDAo, which uses PersonDao and TelephoneNumberDao under the hood to do this.

Alternatively, avoid the whole problem and do not try to match 1-N between the person and the phone number at the DTO level. Just ask your user interface to call the right DAOs correctly. I really like this better when using DTO.

+4
source share

It is generally accepted to introduce a service level that wraps your DAOs and handles such problems. If you are afraid that you use too many code templates in your DTOs to handle lazy loading, perhaps using AOP may be the way to achieve this. You might want to look into AspectJ and weave either at compile time or at boot time. Since you will modify the byte code directly, you don’t have to worry about the overhead of proxy-based AOP performance.

+3
source share

All Articles