I am using Java + Spring framework for a web-application. I am not using any ORM tool. Instead I am trying to model the db relations as Java objects using simple DAO/DTO pattern. Whenever the DTO exactly corresponds to a single table in the database, it is very straight forward. But if there are tables that refer to other tables using foreign keys, I am not sure what is the best approach for this. Looked in Stackoverflow for similar answers but could not find one to my needs. I want to give a very specific example- Suppose there are two entities User and Group. I have a User DTO and Group DTO, each one having UserDao(JdbcUserDao) and GroupDao(JdbcGroupDao) respectively.
Now I have a relation in DB that connects the User and Group. One user can belong to multiple groups. The table name is User_Group_Association that has the following DB definition:
user_id | group_id
Here user_id is a foreign key referring to user table. Similarly group_id refers to group table. When I model this DTO in Java, should I do something like this:
public class UserGroupAssoc {
private int userId;
private int groupId;
//Setters and getters follow
}
OR should it be like this:
public class UserGroupAssoc {
private User user;
private Group group;
//Setters and getters follow
}
Particular UI use case: I want to display usernames and the corresponding group names they belong to. Something like this-
Name -> Group Names
Keshav -> Admin, EndUser, ReportAdmin
Kiran -> ReportAdmin
Pranav -> EndUser
In the first approach to DTO design, I will need to fetch the user details (names) and group details (names) again from the DB. In the second approach, I would need to fetch the User and Group objects when i am constructing the UserGroupAssoc object itself.
In probably a third approach I can design the UserGroupAssoc DTO as follows:
public class UserGroupAssoc {
private String userName;
private String groupName;
private int userId;
private int groupId;
//Setters and getters follow
}
In this third approach, I join tables in SQL to obtain only the needed fields for the use-case and then model the DTO accordingly.
Which is the standard approach to achieve this scenario? Is joining tables alright in the DTO design? Some have opinions that one DTO should correspond to only ONE table and the associated objects should be aggregated in the app layer. That has overhead of doing multiple object fetches from DB right? Too confused about the right approach, sorry for such a long explanation!