I have a project that is using Spring and is broken down into a couple dozen DAOs and associated DTOs. I'm using JdbcTemplate, but not much else, as it's exactly the level of abstraction I'm happy with.
I'm currently performing lazy loading on my DTOs by placing some rather hairy code in their getters.
Basic boilerplate logic is: 1. If field is not null return its value and exit 2. Contact appropriate DAO and fetch relevant DTOs 3. Store them until next time.
It works fine except that my lowly DTOs are coupled with a whole bunch of DAOs and aren't so POJOey.
Another code smell appears if I place the logic in the DAO since it would be handling both CRUD for its DTOs and Lazy Loading, and as I understand it Objects should have a single responsibility.
I'm hoping that there's a relatively simple Spring approach that I can use to inject a Lazy Loader object between the DAOs and the DTOs to achieve this, but any other solution would work for me.
Any ideas?
It's easier to wrap DAO's around DAO's... it depends on how much of the model you want to bring across. DTO's aren't typically used to bring a one to many over with them, as two or more separate database/dao calls. In that case you really want an ORM. Since your looking for a dao answer......
There's nothing stopping you from linking DAO's together to give you one single DTO. It's easier then have a DTO connected to a DAO. It's not really a service layer, it's just building blocks of DAO's. So you might have a PersonDao, and a TelephoneNumberDao. A person can have more then one telephone number, so you could also have PersonModelDAo, that uses PersonDao and TelephoneNumberDao under the hood to do it's work.
Alternatively, avoid the whole problem and don't try to map the 1-N between person and telephone number at the DTO level. Just have your UI make the right calls to the right DAO's. I actually like this better when using DTO's.
It's common to introduce a service layer that wraps your DAOs and handles concerns such as that. If you're afraid you are putting too much boilerplate code into your DTOs to handle lazy loading, perhaps using AOP could be a way to achieve this. You might want to look into AspectJ and weaving either at compile-time or load-time. Since you would be modifying the byte-code directly you wouldn't have to worry about the performance overhead of proxy-based AOP.
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