Hi,
consider the following example. Suppose that we have two entities, Company and Person for example. Both of them need to be able to pass messages to other entities and receive them. For example, a Company must be able to send and receive messages to another Company but also to Persons as well. A Person needs similar functionality.
Furthermore, later on, we may need to add more similar classes, for example NonProfitOrganization. One possible approach is inheritance, e.g. everyone inherits abstract GenericCommunicator and gets the communication functionality via it. However, this prohibits from inheriting other classes (e.g. Company might want to inherit Organization, but Person would not want to do that).
So, I've thought of isolating communication functionality to a separate class and using a has-a relationship to implement it. I believe this is called composition - a brief illustration of what I mean is at the end of this message.
How can I implement this with Hibernate and JPA annotations? I have been unable to find any references to this kind of an arrangement, although it seems a common design pattern. Hibernate would basically need to create two columns to the table corresponding to GenericCommunicator - the type and the ID of the parent object.
Code:
@Entity
public class Company implements Serializable {
private GenericCommunicator communicator = new GenericCommunicator(this);
public GenericCommunicator getCommunicator() {
return communicator;
}
...
}
Code:
@Entity
public class GenericCommunicator implements Communicator, Serializable {
private Serializable parent;
private Set<Message> messages = new HashSet<Message>();
public GenericCommunicator(Serializable parent) {
this.parent = parent;
}
public Serializable getParent() {
return this.parent;
}
public void addMessage(Message message) {
....
}
...
}