I have 2 tables: Document and Category with a many to many relationships. In addition, the relationship has an attribute called weight.
I also have the corresponding Classes with Document being represented like this:
public class Document {
private Integer id; // Id from DB, 0 if new object
private String name;
private String url;
private Date dateCreated;
private List<Category> categories;
// getters & setters...
}
Now I have 2 questions – best practices concerns especially.
I want to retrieve data from the database (MySQL) and and build my objects. I use a SELECT statement like that:
SELECT doc.*, GROUP_CONCAT(cat.CategoryID SEPARATOR ',') AS CategoryGrp FROM document doc
LEFT JOIN doc_category dc ON doc.Doc_ID = dc.DC_DocID
LEFT JOIN category cat ON dc.DC_CategoryID = cat.CategoryID
GROUP BY doc.Doc_ID
In the resultset, rs.getString(5) –> CategoryGrp will have the IDs of the related categories. Now how do I proceed to build my object Document by linking its Categories as the Class requires it.
I tend to do new SELECT request on table Category to get the others details (category name for instance) in a loop while still on the first ResultSet.
Is that a good practice? Isn’t there a “recommended” way?
My second question is about the attribute weight in junction table. In which object should I record its value? I guess it’s Category but not very sure since Category object can’t have a weight on its own…
Hope I have clear enough.
Thanks
Answer to 1st question:
2 ways: one sql or like you suggest 2 sql. (retriev the docs and for every cat id perform sql to retrive cat attributes)
I think this is better:
Get your all docs with different cats and its attributes. Loop it and compare the doc with the previous one. If different, then you have a new doc object. Every line in the loop is a different cat object.
Answer to 2nd question:
I think you should consider this: is the weight more related to doc or cat? On the other hand, you cannot have multiple weights on 1 doc, so my guess would be to add the to cat (as that is a 1 on 1 relationship.