Kohan95
Kohan95

Reputation: 10359

help to create Internal messaging

I want to create an internal messaging system and that is what I did I have a User Entities for user and one for message

I do not know if this is good or not

public class Utilisateur implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

...

}

public class Messagerieinterne implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sujet;
private Long   Idexpiditeur;
private Long IdReceiver ;

.. }

The problem with this solution is I should use nativeQuery method to insert data in database

if you have any suggestions please

for more explanation I want to create a messaging system for my site(JSF2,EJB3,MYSQL) so that users can send messages between them

thank you in advance

Upvotes: 0

Views: 997

Answers (1)

JB Nizet
JB Nizet

Reputation: 691745

The goal of JPA is to be able to create a graph of persistent entities. These entities are linked between them thanks to OneToOne, OneToMany and ManyToMany relationships, in order to be able to navigate into the graph. A Message entity should thus have a receiver field of type User and a sender field, also of type User. You may also model the inverse relationships: a User has many sent messages, and many received messages. You thus have two OneToMany relationships :

  1. One User sends Many Messages
  2. One User receives Many Messages

Your Message class should thus look like this :

public class MessagerieInterne implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sujet;

@ManyToOne(optional = false)
@JoinColumn(name = "ID_EXPEDITEUR", nullable = false)
private Utilisateur expediteur;

@ManyToOne(optional = false)
@JoinColumn(name = "ID_DESTINATAIRE", nullable = false)
private Utilisateur destinataire;

And you might have additional fields in your User class :

public class Utilisateur implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(mappedBy = "expediteur")
private List<MessagerieInterne> messagesEnvoyes;

@OneToMany(mappedBy = "destinataire")
private List<MessagerieInterne> messagesRecus;

Think in terms of objects instead of thinking in termes of fields in a database table. Also, please respect the Java naming conventions (variables starting with a lowercase, camelCase, etc.), and avoid mixing French and English terms.

With such entities, I don't see why you couldn't use EJBQL and regular JPA methods to insert and read messages in database.

Upvotes: 2

Related Questions