Reputation: 13342
Let's say we have two classes: Software and Tag. Software can be related to many tags and each tag could be related to many Softwares. So, we have Many-To-Many relationship.
We use Hibernate and annotations:
@Entity
class Software .. {
@ManyToMany
public List<Tag> tags = new LinkedList<Tag>();
...
}
@Entity
class Tag .. {
@ManyToMany(mappedBy = "tags")
List<Software> softwares = new LinkedList<Software>();
...
}
Then, every time when we want to add existing tag to the software, we need to add this software to that tag (to keep right many-to-many structure). Like this:
class Software {
...
public void add(Tag tag) {
tags.add(tag);
tag.add(software);
}
...
}
If this adding tag already related to 1000 0000 softwares, then at the moment we call tag.add(sofware), Tag class will download all those softwares into memory in order to just add one software to it. Right?
The question: what is the best practice how to avoid this?
Upvotes: 1
Views: 292
Reputation: 6289
Hibernate allows you to think about the database schema in the object-oriented way. But when you get to reasonably complex or reasonably large data, you should still keep realtional database realities in your mind. Your many-to-many realtionship in the database would be implemented as a separate table with the foreign keys to the table representing tags and to the table representing software. For your situation, I'd add a class SoftwareTag to represent that many-to-many mapping table, change the class Software to conatin a list of SoftwareTags, and would remove any collections from the class Tag. Based on your business logic you might need to add some findBy methods to your DAOs but that should be trivial.
Upvotes: 1