Hi
This is a design pattern question. Here is the scenario:
I am using EJB3.0 with JPA. For example lets say I have a user who can belong to groups. So in my User entity I have a method getGroups() which fetches the groups lazily. And I have a UserDao which is a stateless session bean which has a method
User getUser(int uid)
Now in my JSF backing bean I inject the remote interface of UserDao and call getUser on it to get the User bean. But I cannot access user.getGroups because it is a detached entity. So I can think of three approaches here:
- In my dao method I eagerly fetch the groups also so that they are accessible in the remote User entity also. But issue with this is Group itself might have lazily fetched relation and those also I will have to eagerly fetch and those might have more lazily fetched relation and so on. So I will end up sending a heavy weight object most of whose properties I will not need.
I send User as it is and rely on my client to not call getGroups on it. I can provide a separate method in userdao which is
List<Integer> getGroupsIds(int userId)
And I have a GroupDao which has similar methods getGroup(int groupId) and other methods to get Ids of lazy relations.Third option is to not send these JPA entities across at all and create other POJOs like UserInfo,GroupInfo etc that just contains the basic attributes of each entity and send these across. And I can have methods in DAOs to get these entities for different relations like:
List<GroupInfo> getGroupsForUser(int uid)
List<UserInfo> getUsersInGroup(int gid)
So which of these is a preferred pattern. Or is there some other pattern that people use here?