I have been looking into private messaging database schemas and currently I am trying to build a basic db schema to store and retrieve messages - nothing too complex. This is the Message entity:
@Entity
@Table(name="messages")
class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id", unique=true, nullable = false)
private int id;
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "thread_id")
private Thread thread_id;
@Column(name="sent_date")
private Date sent_date;
@Column(name="message_body")
private String message_body;
@JoinColumn(name = "sender_id")
private User sender;
@JoinColumn(name = "receiver_id")
private User receiver;
// getters and setters
}
and the Thread entity is just an id :
@Entity
@Table(name="threads")
class Thread {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id", unique=true, nullable = false)
private int id;
// getters and setters
}
this is the method that calls my query:
public List<Message> getDistinctMessagesForUser(int id) {
return em.createQuery("SELECT m FROM Message m WHERE m.thread_id IN (SELECT DISTINCT m.thread_id FROM Message m WHERE (m.sender.id =:id OR m.receiver.id =:id)) ORDER BY m.sent_date DESC", Message.class)
.setParameter("id", id)
.getResultList();
}
I am using HQL to query the db. I am trying to get the most recent messages for each thread using a SELECT DISTINCT but I can't seem to make it work.
I tried using this :
SELECT m FROM Message m WHERE (m.sender.id =:id OR m.receiver.id =:id) GROUP BY m.thread_id ORDER BY m.sent_date DESC)
but I kept getting this error:
ERROR: column "message0_.id" must appear in the GROUP BY clause or be used in an aggregate function
I also tried the method shown in this link but the error was as a result of the fact that the query had e and m.
Every other query I tried returned either all the messages (instead of distinct) or threw the error I described above. I do not want to use CriteriaAPI as I read that it is a slower than HQL, and the other code I have is written in HQL and I plan to stick to one method. What am I missing?
SELECT m, m.thread_Id FROM Message m WHERE (m.sender.id =:id OR m.receiver.id =:id) GROUP BY m.thread_id ORDER BY m.sent_date DESC)- fg78ncjava.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [Message]- Aria