I have a query in Data Access Object DAOComments that joins users table and comments table and then store the result into Data Transfer Object DTOComments:
private static final String SQL_FIND_WITH_USERNAME =
"SELECT u.username, comments.* FROM users u JOIN comments
ON u.id = comments.id ORDER BY created_date DESC LIMIT 10;";
However, DTOComments does not have property “username” since it is the property of DTOUsers.
Option 1
So I decided to use Map<String, DTOComments>
In this case the map has username as KEY, DTOComments as VALUE.
But this approach will fails, because I care about the ORDER of result and that’s why my query returns result in descending order. If I iterate the map on JSP page, the order is not consistent, so my JSP page would output the comment in random order.
(Even if order doesn’t matter, I don’t know if JSTL can display map’s KEY. I know displaying the VALUE though)
Option 2
I could put the query result into ArrayList<DTOComments>
But I don’t see any room to store the "username" now. Maybe I can add new property to DTOComments like private String username;
hmm… this would violate the concept of having DTO since it SHOULD reflect the database table schema.
Option 3
Create new class that hold all the information I need (ie. username + properties of DTOComments).
But just because I need one more property “username” in addition to the properties of DTOComments, creating new class seems not right way.
Could anyone give me advice how can I store all info returned by the query above in more organized way?
That’s the nature of
HashMap. If you want to maintain insertion order in aMap, then you should be usingLinkedHashMapinstead. But theMap<User, Comment>approach has another disadvantage, if an user has posted more than one comment, you would be overwriting the previously inserted comment this way. You would like to use aMap<Comment, User>instead.But IMHO it’s better to make the
Usera property inCommentclass, indicating a many-to-one relationship:This way you can end up with a
List<Comment>.That said, I wanted to comment on another statement of you:
You can iterate over a map using
<c:forEach>. It goes overMap#entrySet(). Each iteration gives aMap.Entryobject back which in turn hasgetKey()andgetValue()methods.Here’s a kickoff example: