0

如何在 Hibernate 实体类中创建下一种关系?用户通过创建消息(发送者、接收者、消息)向另一个用户发送消息。数据库看起来像这样:

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

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

实体类必须是什么样子?

@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;
}

映射...什么?我需要找到所有消息,其中当前用户作为发送者 OR/AND 接收者存在。(“AND”,因为用户可以向自己发送消息)。

4

1 回答 1

1

如果您需要查找用户发送或接收的消息,您已经在消息实体中拥有所有信息,并且用户映射对您来说并不重要。

从消息 m 中选择 m,其中 m.sender!=m.receiver 和(m.sender=:user 或 m.receiver=:user)。

有两种类型的关系:单向和双向。

如果在用户的实体映射中,您应该保留有关发送者和接收者的信息(您已经在消息中拥有此信息)然后是方向关系:

@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;
}
于 2017-06-16T03:31:09.737 回答