javahibernateone-to-manyhibernate-onetomanymappedby

Hibernate user messages relation


How to create next type of relation in Hibernate entity classes? User sends message to another user by creating message (sender, receiver, message). DB looks like this:

+-----------------------------------+
|                user               |
+-----------------------------------+
| id |   nickname  |    password    |
+----+-------------+----------------+
|  1 |    admin    |      pass      |
+----+-------------+----------------+

+------------------------------------------------+
|                     message                    |
+-----------------------------------|------------+
| id |  sender_id  |  receiver_id   |  message_t |
+----+-------------+----------------+------------+
|  1 |      10     |       12       |      hi    |
+----+-------------+----------------+------------+

How entity classes must be look like?

@Entity 
@Table(name="profiles")
public class Message {

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

    @ManyToOne
    @JoinColumn(name = "sender")
    private User sender;

    @ManyToOne
    @JoinColumn(name = "receiver")
    private User receiver;

    @Column(name = "message")
    String message;
}

@Entity
@Table(name = "users")
public class User {

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

    @OneToMany(mappedBy = )
    List<Message> messages;
}

Mapped by.. what? I need to find all messages, where current user exists as a sender OR/AND receiver. ("AND" because user can sends a message to himself).


Solution

  • if you need to find messages sended or recived by user you alread have all information in Message entity and user mapping doesn't matter for you.

    select m from Message m where m.sender!=m.receiver and (m.sender=:user or m.receiver=:user).

    there are two type on relationship: unidirectional and bidirectional.

    if in entity mapping for user you should keep information about sender and reciver (you already have this information in Message) then dibirectional relationship:

    @Entity
    @Table(name = "users")
    public class User {
    
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @OneToMany(mappedBy = receiver)
        private List<Message> messagesRecived;
    
        @OneToMany(mappedBy = sender)
        private List<Message> messagesSended;
    }