I was reading Apress "Beginning Spring 2 From Novice to Professional", and I found this one section that discusses usage of DAOs. The example is pretty simple and I have pasted the src here:
- UserAcccount.java - UserAccount Entity
- UserRole.java UserRole Entity
- UserAccountDao.java - UserAccount DAO
- JdbcUserAccountDaoImpl.java - JDBC Implementation of the UserAccount DAO
Advanced java/spring users can directly refer to the last link (jdbc implementation of the DAO). What interests me is this piece of the source code:
public List<UserAccount> list() {
final List<UserAccount> list =
getTemplate().query(SELECT_ACCOUNTS, userMapper);
for(final UserAccount account : list) {
populateRoles(account);
}
return list;
}
This method is supposed to retrieve a list of all the UserAccounts in the database. The first list obtained by executing the query "SELECT_ACCOUNTS" only gets you the UserAccount details from the UserAccount table. The UserRoles however are on a different table. From the above piece of code, it is quite clear that for every UserAccount, populateRoles is executed. populateRules(account) in turn queries the roles table with the user id. Effectively, if you have 1000 users, this code would fire out a prepared statement 1,000 times!!
So here come the questions:
Section 1:
Isn't that a bad practice? Is there an easy way to this? How would you do it normally? What is the best-practice here?
Section 2:
How do you decide on DAOs? Should each entity have a DAO? For instance, in the above example, UserAccount and UserRoles represent two entities. On the database front, you have USERS, ROLES tables for the same and a USERS_ROLES mapping table. So, how would you decide on what DAOs to create? Does it depend on requirements? Or should I create a DAO when objects are related (have a mapping table in the database?)?