I have two classes that I want related to each other in an JEE application using JPA2. In an OO world, I would say that a Chatroom has an attribute List messages. In the relational world composition doesn't exist like this. If I weren't involving a database at all, I would definitely code these two things as a composition the messages inside of the Chatroom. But since I'm using ORM with the JPA2 spec I've decided to try to create the @Entity objects as written below with the fact that they'll be mapped to the database in mind.
My question is: Should I be doing this? Is it appropriate to break out the @Entity classes to support what feels like the more relational approach? Or should I just design from an OO perspective, and try to ignore the fact that there's an ORM driving it from below? Right now I'm driving my design from the database side, but should I be doing it the other way? Are there implications I'm missing about doing it this way?
package org.janp.castlerock;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Chatroom {
private String name;
@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.janp.castlerock;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Message {
private int id;
private Chatroom chatroom;
private Date timestamp;
private String text;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@ManyToOne
@JoinColumn(name="name")
public Chatroom getChatroom() {
return chatroom;
}
public void setChatroom(Chatroom chatroom) {
this.chatroom = chatroom;
}
}