0

I have a table/class User and Message. One User can have many messages. How do I model the Java class for Message; should it have a property of type User, or just a String for the username which is the key in this relationship?

When using Hibernate to generate the classes, it gave the Message class a User property. Does that mean it's the right way?

I find it problematic when creating messages to also give it a User instance, because I can't seem to do that in a Spring webflow that I'm using (I'm only passing the username from the view).

1 Answers1

0

you can design your class with a OneToMany relation and Message class does not need to have an user field.

For exemple :

public class User {
 @OneToMany
 private List<Message> messages;
}

public class Message {
 @Basic
 private String body;
}

In this case, the database table for Message will have a column for the user id. You can specify another columnn by using JoinColumn :

public class User {
 @OneToMany
 @JoinColumn(name="my_user_id_column")
 private List<Message> messages;
}

Otherwise, you can use @JoinTable like in this answer

victor gallet
  • 1,819
  • 17
  • 25
  • But if Message doesn't have a user or username field, how can I tell which user it belongs to? When I insert a message into the database, how can I get a value to fill the user id column with? – Jonathan Andersson Nov 06 '15 at 11:13
  • In my proposition, you should add a Message to an User and not add an User to a Message. So, you will have all the messages owned by an user. If you really want to add an User to a Message you can by adding a relation `@ManyToOne` to the Message Entity. – victor gallet Nov 06 '15 at 12:13
  • I think I understand now after watching the video in @sanjay's answer. Would you say that this approach is in general superior to having a ManyToOne in Message? For my purposes it seems like having a ManyToOne in Message fits better though. But then the question is, if I go with that approach, should the ManyToOne map to a User object, or just a String (username) object, since that's what will be used in the MessageDao anyway? – Jonathan Andersson Nov 08 '15 at 10:11
  • it should be map to a User. – victor gallet Nov 08 '15 at 10:27
  • Ok thank you! That makes the most sense although I doubted it since it got more tedious to get the username. – Jonathan Andersson Nov 08 '15 at 12:47