我正在使用Hibernate和Postgres的Spring-MVC应用程序。在应用程序中,我正在添加聊天功能。我使用一个非常简单的数据库模式来保存聊天。在模式中,对于表Messages,有2个外键,称为User User作为发送者和接收者。 我目前能够发送和接收消息,但问题是我想将消息加入到用户之间的对话中。我有按时间对邮件进行排序的时间戳,但我不知道如何将其他用户(收件人名称)分组并将其显示在前端(HTML)
我发布了一些代码和架构,请好好看看:
SQL代码:
CREATE TABLE public.userinfo (
id INTEGER NOT NULL,
email VARCHAR,
username VARCHAR,
displayname VARCHAR,
password VARCHAR,
CONSTRAINT id PRIMARY KEY (id)
);
CREATE TABLE public.conversation (
conversation_id NUMERIC NOT NULL,
messagetext VARCHAR,
time DATE,
id INTEGER NOT NULL,
userinfo_id INTEGER NOT NULL,
CONSTRAINT conversation_id PRIMARY KEY (conversation_id)
);
ALTER TABLE public.conversation ADD CONSTRAINT userinfo_conversation_fk
FOREIGN KEY (id)
REFERENCES public.userinfo (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE public.conversation ADD CONSTRAINT userinfo_conversation_fk1
FOREIGN KEY (userinfo_id)
REFERENCES public.userinfo (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
MessagesDAOImple:
@Override
public boolean addMessage(User sender, User receiver, Messages messages) {
if( session == null) {
session = this.sessionFactory.openSession();
}else {
session = this.sessionFactory.getCurrentSession();
}
int id = sender.getId();
User sender1 = (User) session.get(User.class,id);
sender.getMessages1().add(messages);
receiver.getMessages2().add(messages);
session.saveOrUpdate(messages);
session.flush();
return true;
}
@Override
public List<Messages> listMessagesForUser(User user) {
if(session == null){
session = this.sessionFactory.openSession();
} else{
session = this.sessionFactory.getCurrentSession();
}
int id = user.getId();
Query query = session.createQuery("from Messages as m where m.user2.id=:id");
query.setParameter("id",id);
List<Messages> messagesList= query.list();
return messagesList;
}
我仍在编写html代码,所以我现在还没有,但是如果有可能使用像c:forEach这样简单的东西,并将消息显示为按对话分组的测试列表是什么我在寻找。任何指针或建议都会很好。谢谢。
答案 0 :(得分:1)
我不确定你在寻找什么。
这是一些返回两个用户(123&amp; 321)之间对话的SQL
SELECT * FROM (
SELECT * from conversation WHERE id = 123 and user_info_id = 321
UNION
SELECT * from conversation WHERE id = 321 and user_info_id = 123
) conv ORDER BY time ASC
以下是获取用户123&amp;的所有会话的查询。和任何合作伙伴
SELECT * FROM (
SELECT user_info_id AS partner_id, * from conversation WHERE id = 123
UNION
SELECT id AS partner_id, * from conversation WHERE user_info_id = 123
) conv ORDER BY partner_id, time ASC
使用上述内容将要求您循环搜索结果并决定通过partner_id显示不同的会话伙伴。
为避免循环,您可能需要考虑聚合函数,但我不确定此处GROUP BY子句的性能。
SELECT partner_id, array_agg(messagetext) FROM (
SELECT * FROM (
SELECT user_info_id AS partner_id, * from conversation WHERE id = 123
UNION
SELECT id AS partner_id, * from conversation WHERE user_info_id = 123
) conv ORDER BY time ASC
) conv_aggs GROUP BY partner_id
protip ..你可能想要array_to_json(array_agg(messagetext))