title: JPA Query/Hibernate: Column must appear in the GROUP BY clause or be used in an aggregate function
body: <p>I have the following table <code>session</code>:</p>
  
  <pre><code>sessionid | user_id | begin (timestamp)
  ----------+---------+-------------------
       1    |    A    |  1234
       2    |    B    |  4567
       3    |    A    |  8912
       4    |    C    |  3456
  </code></pre>
  
  <p>The table gives information about the sessions of a user. Basically, a session is when a user has performed a successful login.</p>
  
  <p>Now, I want to get a list of the users which have logged in most recently. If a user has more than one login (and occures twice or more in this table), I use the most recent timestamp for it. The list should be ordered by logintime, so that the most recent users are at top of the list.</p>
  
  <p>Using the following SQL query I solved this:</p>
  
  <pre><code>SELECT s.user_id, MAX(begin) -- MAX(begin) can be left out, results are the same
  FROM session s
  GROUP BY s.user_id
  ORDER BY MAX(s.begin) DESC
  </code></pre>
  
  <p>However, in my application I am supposed to use a JPA Query for this. So I converted this to the following JPA Query:</p>
  
  <pre><code>SELECT s.user
  FROM Session s
  GROUP BY s.user
  ORDER BY MAX(s.begin) DESC
  </code></pre>
  
  <p>I select here the user and not the user_id because User is an Entity in Session. We are using Hibernate as well, and when executing this query, I get the following error:</p>
  
  <p><code>ERROR [org.hibernate.util.JDBCExceptionReporter] ERROR: column "user1_.id" must appear in the GROUP BY clause or be used in an aggregate function</code></p>
  
  <p><a href="https://hibernate.onjira.com/browse/HHH-1615" rel="nofollow">I found a bug description about this behaviour on Hibernate.</a></p>
  
  <p>Using the <code>s.user.id</code> instead works fine, but it gives me only the IDs and I need the user Objects.</p>
  
  <p>I made a workaround now by getting the user ids first and then find the user entities in the database, but this needs an additional database call and seems unperformant to me, as I know that it can be done within one query.</p>
  
  <p>How to solve this problem?</p>
  
  <p>I am not allowed to use SQL queries directly in the application, I must do it using the JPA Query approach.</p>