Question

I'm trying to implement a model for private messages between two or more users.

That means I've got two Entities:

  • User
  • PrivateMessage

The User model shouldn't be edited, so I'm trying to set up an unidirectional relationship:

@Entity (name = "User")
@Table (name = "user")
public class User implements Serializable {
@Id
String username;
String password;
// something like this ...
}

The PrivateMessage Model addresses multiple receivers and has exactly one sender. So I need something like this:

@Entity (name = "PrivateMessage")
@Table (name = "privateMessage")
@XmlRootElement
@XmlType (propOrder = {"id", "sender", "receivers",
        "title", "text", "date", "read"})
public class PrivateMessage implements Serializable {

    private static final long serialVersionUID = -9126766942868177246L;

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    private String title;

    @NotNull
    private String text;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @NotNull
    private boolean read;

    @NotNull
    @ElementCollection(fetch = FetchType.EAGER, targetClass = User.class)
    private Set<User> receivers;

    @NotNull
    @OneToOne
    private User sender;

    // and so on
}

The according 'privateMessage' table won't be generated and just the relationship between the PM and the many receivers is satisfied. I'm confused about this. Everytime I try to set a 'mappedBy' attribute, my IDE marks it as an error.

It seems to be a problem that the User-entity isn't aware of the private message which maps it.

What am I doing wrong here? I've solved some situation similar to this one, but none of those solutions will work here.

Thanks in advance!

Was it helpful?

Solution

I now know the answer to my problems:

The field 'read' is a reserved key word of MySQL: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

So I changed the field to unread and now the table is generated successfully.

Furthermore, I think the correct Mapping from PrivateMessage to User is @ManyToMany because there can be several User adressed in a PM and also Users can receive several PMs. The field 'sender' remains @OneToOne.

Now all tables are generated successfully. The main problem was, that I've used the reserved MySQL-keyword and that prevented the generation of the table. When that problem was solved, it was easy to figure out the correct configuration of the mappings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top