JAVA持久性顺序在Group By之前

时间:2014-12-03 17:54:54

标签: java java-ee persistence jpql

我们需要由发射器获取最后一个帖子消息组。

Query query = em.createQuery("SELECT m FROM Message m " + "JOIN m.transmitter " + "JOIN m.recipient " + "WHERE m.transmitter = :u1 " + "OR m.recipient = :u1 " + "GROUP BY m.recipient,m.transmitter " + "ORDER BY m.sendDate DESC"); query.setParameter("u1", actualUser);

但是我们需要这样的东西,我们得到最早的信息:

Query query = em.createQuery("SELECT m FROM Message m " + "JOIN m.transmitter " + "JOIN m.recipient " + "WHERE m.transmitter = :u1 " + "OR m.recipient = :u1 " + "ORDER BY m.sendDate DESC" "GROUP BY m.recipient,m.transmitter "); query.setParameter("u1", actualUser);

感谢您对我的英语表示抱歉。

2 个答案:

答案 0 :(得分:0)

也许是这样的?

Query query = em.createQuery("SELECT m FROM Message m " +
                "WHERE m.sendDate = (" +
                "SELECT MAX(m.sendDate) FROM MESSAGE m "
                "JOIN m.transmitter t " +
                "JOIN m.recipient r " +
                "WHERE t = :u1 " +
                "OR r = :u1)");
        query.setParameter("u1", actualUser);

答案 1 :(得分:0)

我的解决方案是首先获取所有联系人,然后从联系人那里获取最后一封发送消息(两个查询而不是一个大查询。